Java stream常用方法

SerializerFeature.WriteMapNullValue//List字段如果为null,输出为[],而非null
List list = new ArrayList();
List list = Lists.newArrayList();
Lists.newArrayList()其实和new ArrayList()几乎一模一样
Map<String, Object> result = new HashMap<String,Object>();
Maps.newHashMap();
MapUtils
ListUtils
SetUtils
CollectionUtils
StringUtils

List listNos = Arrays.asList(“3232”,“432423”);
for(int i = 0; i < listNos.size() / 500f; i++) {
int fromIndex = 500 * i;
int toIndex = 500 * (i + 1);
if (toIndex > listNos.size()) {
toIndex = listNos.size();
}
List listNoUpdates = listNos.subList(fromIndex, toIndex);
System.out.println(listNoUpdates);
}
Integer times = (3 + 100 - 1) / 100;
for (int i = 0;i < times;i ++) {
System.out.println(times);
}

List list = Collections.synchronizedList(new ArrayList())
Iterator i = list.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
stream
parallelStream是利用多线程进行的,这可以很大程度简化我们使用并发操作,forEachOrdered与forEach一样
list.parallelStream().forEachOrdered(num->{})
BATCH =500;
IntStream.range()产生指定区间的有序IntStream,这里需要传入一个区间(左闭右开),产生的元素不包含最后一个
mapToObj()转成对象流,
IntStream.range(0, (intObjectListSize + BATCH - 1) / BATCH)
.mapToObj(i -> objectList.subList(i * BATCH, Math.min(BATCH * (i + 1), intObjectListSize)))
.parallel().map(list -> setEachBatchData(list, mapBasicParam, mapBusinessParam, hxStkIpImgList, exist, hxStkIpImgUpdateList, tempOwnerId)
).collect(Collectors.toList());

//map转list
map.entrySet().stream().map(e -> new Person(e.getKey(),e.getValue())).collect(Collectors.toList());
//list转set
Set set = list.stream.collect(Collectors.toSet());
Map<String, String> mapStr = list.stream().collect(Collectors.toMap(student -> student.getStuId().toString(), student -> JSON.toJSONString(student)));
Collections.sort(list, (o1, o2) -> {
if (o1.getName().compareTo(o2.getName()) > 0) {
return 1;
} else if (o1.getName().compareTo(o2.getName()) < 0) {
return -1;
} else {
return 0;
}
});

//List根据某个字段过滤、排序
listStu.stream().filter(student -> student.getSex().equals(“女”)).sorted(Comparator.comparing(Student::getName)) .collect(Collectors.toList());
//List根据某个字段分组
Map<String,List> sexGroupMap = listStu.stream() .collect(Collectors.groupingBy(Student::getSex));
//如果Map中多个名称相同,则studentId用逗号间隔
Map<String,String> studentNameIdMap = listStu.stream().collect(toMap(Student::getName,Student::getStuId,(s,a)->s+","+a));
//List转map
Map<String, String> map = list.stream().collect(Collectors.toMap(Student::getStuId, Student::getName));
map.forEach((key, value) -> {
System.out.println(“key:” + key + “,value:” + value);
});
//key为stuid,value为对象
Map<String, Object> map = list.stream().collect(Collectors.toMap(Student::getStuId, student -> student));
Map<String, Object> map = list.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2));
//从list取某个字段集合
List result = list.stream().map(student -> student.getName()).collect(Collectors.toList());
for (String name : result) {
System.out.println(“name:” + name);
}

int is = StringUtils.countMatches(“213@adaasd”, “@”);

// 对象根据年龄属性升序排序
List newList = list.stream().sorted(Comparator.comparing(User::getAge)).collect(toList());

    // 对象根据年龄属性降序排序
    List<User> newList = list.stream().sorted(Comparator.comparing(User::getAge).reversed()).collect(toList());

    // 标识升序,再按创建日期降序
    // List<BhAnnouncement> newList =announcementList.stream().sorted(Comparator.comparing(BhAnnouncement::getReadFlag).thenComparing(BhAnnouncement::getSendTime).reversed()).collect(toList());

    // list遍历
    newList.forEach(System.out::println);

    // 平均数
    double asDouble = list.stream().mapToLong(User::getAge).average().getAsDouble();
    System.out.println("average:" + asDouble);

    double avg = list.stream().collect(Collectors.averagingLong(User::getAge));
    System.out.println("average:" + avg);

    // 最大值
    long asLong = list.stream().mapToLong(User::getAge).max().getAsLong();
    System.out.println("max:" + asLong);

    // 最小值
    long asLong1 = list.stream().mapToLong(User::getAge).min().getAsLong();
    System.out.println("min:" + asLong1);

    // 求和
    long sum1 = list.stream().mapToLong(User::getAge).sum();
    System.out.println("sum:" + sum1);

    // 提取对象属性生成list
    List<Long> ids = list.stream().map(User::getAge).collect(toList());
    System.out.println(ids);

    // list升序排序
    Collections.sort(ids);
    System.out.println(ids);

    // 生成中位数
    Long j;
    if (ids.size() % 2 == 0) {
        j = (ids.get(ids.size() / 2 - 1) + ids.get(ids.size() / 2)) / 2;
        System.out.println("中位数为" + j);
    } else {
        j = ids.get(ids.size() / 2);
        System.out.println("中位数为" + j);
    }

    // list倒序排序
    ids.sort(Comparator.reverseOrder());
    System.out.println(ids);

    // 去重
    List<User> users = list.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(comparingLong(User::getAge))), ArrayList::new));
    System.out.println("去重:"+users);

    /**
     * List -> Map
     * 需要注意的是:toMap 如果集合对象有重复的key,会报错Duplicate key ....
     *  apple1,apple12的id都为1。可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
     */
    Map<Long, User> userMap = list.stream().collect(Collectors.toMap(User::getAge, a -> a, (k1, k2) -> k1));
    System.out.println(userMap);

    //过滤出符合条件的数据
    List<User> filterList = list.stream().filter(a -> a.getName().equals("李四")).collect(toList());
    System.out.println("filterList:" + filterList);


    List<Integer> list2 = Arrays.asList(1, 2, 3, 4, 5);

    int sum = list2.stream().reduce(0, (acc, value) -> acc + value);
    System.out.println(sum);

    List<Integer> result = list2.stream().filter((value) -> value > 2).collect(toList());
    result.forEach(System.out::println);

    List<String> result2 = list2.stream().map(value -> String.format("String:%s", value)).collect(toList());
    result2.forEach(System.out::println);

    // 用于收集统计数据的状态对象,例如count,min,max,sum和平均。
    IntSummaryStatistics stats = list2.stream().mapToInt((x) -> x).summaryStatistics();
    System.out.println("Max : " + stats.getMax());
    System.out.println("Min: " + stats.getMin());
    System.out.println("Sun: " + stats.getSum());
    System.out.println("Average : " + stats.getAverage());
    System.out.println("Count : " + stats.getCount());
    System.out.println("toString : " + stats.toString());

@TransactionConfiguration(defaultRollback = false)
@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
@Transactional(rollbackFor = {Exception.class})
@Transactional(noRollbackFor = RuntimeException.class)
List data = Data.getData();
过滤
List collect = data
.stream()
.filter(person -> “男”.equals(person.getSex()))
.collect(toList());
提取
List collect = data.stream().map(person -> person.getName()).collect(toList());
排重
Set collect = data.stream()
.map(PersonModel::getName)
.collect(Collectors.toSet());
List distinctList = list.stream().distinct().collect(Collectors.toList());
list转map
Map<String, Integer> collect = data.stream()
.collect(
Collectors.toMap(PersonModel::getName, PersonModel::getAge)
);
TreeSet collect = data.stream()
.collect(Collectors.toCollection(TreeSet::new));
分组
Map<Boolean, List> collect = data.stream() .collect(Collectors.groupingBy(per -> “男”.equals(per.getSex())));Book::getCategoryId
分隔
String collect = data.stream()
.map(personModel -> personModel.getName())
.collect(Collectors.joining(",", “{”, “}”));
同步
long start1=System.currentTimeMillis();
list.stream().collect(Collectors.toSet());
System.out.println(System.currentTimeMillis()-start1);
并发
long start2=System.currentTimeMillis();
list.parallelStream().collect(Collectors.toSet());
System.out.println(System.currentTimeMillis()-start2);
[1,2,3,4]=>[1,4,9,16]
Integer[] nums1 = {1, 2, 3, 4};
List nums1List = Arrays.asList(nums1);
List res1 = nums1List.stream().map(i -> i * i).collect(Collectors.toList());
List numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
获取对应的平方数
List squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
获取空字符串的数量
int count = strings.stream().filter(string -> string.isEmpty()).count();
过滤非空
List filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
自然序列
List studentList1=studentList.stream().sorted().collect(Collectors.toList());
逆序
List studentList2=studentList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
根据年龄自然顺序
List studentList3=studentList.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
根据年龄逆序
List studentList4=studentList.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
List sortList = list.stream().sorted((a, b) -> a.getId() - b.getId()).collect(Collectors.toList());

list.stream().mapToDouble(User::getHeight).sum()
最大
list.stream().mapToDouble(User::getHeight).max()
最小
list.stream().mapToDouble(User::getHeight).min()
平均值
list.stream().mapToDouble(User::getHeight).average()
double sum = list.stream().mapToDouble(t -> t.getScore()).sum()
int count = list.stream().mapToInt(t -> t.getId()).sum();
分组
Map<Person.Sex, List> collect = roster.stream()
.collect(
Collectors.groupingBy(Person::getGender)
);
遍历
for(Map.Entry<Integer, List> entry : map.entrySet()){
System.out.println(“key:”+entry.getKey());
System.out.println(“value:”+entry.getValue());
}
collect.forEach((k,v) -> System.out.println(k + " : " + v));
根据id求score的统计数据(求和,个数,平均数,最大最小值)
Map<Integer, IntSummaryStatistics> collect = students.stream().collect(Collectors.groupingBy(Student::getId, Collectors.summarizingInt(Student::getScore)));
System.out.println(collect);
Map<Integer, Integer> collect1 = students.stream().collect(Collectors.groupingBy(Student::getId, Collectors.summingInt(Student::getScore)));
Bean bean2 = new Bean(4, 5);
Bean bean3 = new Bean(7, 8);
List list = Lists.newArrayList(bean1, bean2, bean3);
long total1 = list.stream().map(Bean::getNum1).reduce(Long::sum).get();
double total2 = list.stream().map(Bean::getNum2).reduce(Double::sum).get();
//统计研发部的人数,使用 counting()方法进行统计
Long departCount = userList.stream().filter(user -> user.getDepartment() == “研发部”).collect(Collectors.counting());
//统计30岁以上的人数,使用 count()方法进行统计(推荐)Long ageCount = userList.stream().filter(user -> user.getAge() >= 30).count();//统计薪资大于1500元的人数Long salaryCount = userList.stream().filter(user -> user.getSalary().compareTo(BigDecimal.valueOf(1500)) == 1).count();

List data = Data.getData();
过滤
List collect = data
.stream()
.filter(person -> “男”.equals(person.getSex()))
.collect(toList());
提取
List collect = data.stream().map(person -> person.getName()).collect(toList());

排重
Set collect = data.stream()
.map(PersonModel::getName)
.collect(Collectors.toSet());

List distinctList = list.stream().distinct().collect(Collectors.toList());

list转map
Map<String, Integer> collect = data.stream()
.collect(
Collectors.toMap(PersonModel::getName, PersonModel::getAge)
);

TreeSet collect = data.stream()
.collect(Collectors.toCollection(TreeSet::new));
分组
Map<Boolean, List> collect = data.stream() .collect(Collectors.groupingBy(per -> “男”.equals(per.getSex())));

分隔
String collect = data.stream()
.map(personModel -> personModel.getName())
.collect(Collectors.joining(",", “{”, “}”));

同步
long start1=System.currentTimeMillis();
list.stream().collect(Collectors.toSet());
System.out.println(System.currentTimeMillis()-start1);

并发
long start2=System.currentTimeMillis();
list.parallelStream().collect(Collectors.toSet());
System.out.println(System.currentTimeMillis()-start2);

[1,2,3,4]=>[1,4,9,16]
Integer[] nums1 = {1, 2, 3, 4};
List nums1List = Arrays.asList(nums1);
List res1 = nums1List.stream().map(i -> i * i).collect(Collectors.toList());

List numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
获取对应的平方数
List squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());

获取空字符串的数量
int count = strings.stream().filter(string -> string.isEmpty()).count();

过滤非空
List filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());

自然序列
List studentList1=studentList.stream().sorted().collect(Collectors.toList());

逆序
List studentList2=studentList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

根据年龄自然顺序
List studentList3=studentList.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());

根据年龄逆序
List studentList4=studentList.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());

List sortList = list.stream().sorted((a, b) -> a.getId() - b.getId()).collect(Collectors.toList());


list.stream().mapToDouble(User::getHeight).sum()

最大
list.stream().mapToDouble(User::getHeight).max()
最小
list.stream().mapToDouble(User::getHeight).min()

平均值
list.stream().mapToDouble(User::getHeight).average()

double sum = list.stream().mapToDouble(t -> t.getScore()).sum()
int count = list.stream().mapToInt(t -> t.getId()).sum();

分组
Map<Person.Sex, List> collect = roster.stream()
.collect(
Collectors.groupingBy(Person::getGender)
);

遍历
for(Map.Entry<Integer, List> entry : map.entrySet()){
System.out.println(“key:”+entry.getKey());
System.out.println(“value:”+entry.getValue());
}

collect.forEach((k,v) -> System.out.println(k + " : " + v));

根据id求score的统计数据(求和,个数,平均数,最大最小值)
Map<Integer, IntSummaryStatistics> collect = students.stream().collect(Collectors.groupingBy(Student::getId, Collectors.summarizingInt(Student::getScore)));
System.out.println(collect);

Map<Integer, Integer> collect1 = students.stream().collect(Collectors.groupingBy(Student::getId, Collectors.summingInt(Student::getScore)));

Bean bean2 = new Bean(4, 5);
Bean bean3 = new Bean(7, 8);
List list = Lists.newArrayList(bean1, bean2, bean3);

long total1 = list.stream().map(Bean::getNum1).reduce(Long::sum).get();
double total2 = list.stream().map(Bean::getNum2).reduce(Double::sum).get();

//计算平均年龄
double aveAge = userList.stream().collect(Collectors.averagingDouble(User::getAge));
//计算年龄总和
int sumAge = userList.stream().collect(Collectors.summingInt(User::getAge));
//获取IntSummaryStatistics对象
IntSummaryStatistics ageStatistics = userList.stream().collect(Collectors.summarizingInt(User::getAge));
//统计:最大值、最小值、总和、平均值、总数System.out.println(“最大年龄:” + ageStatistics.getMax());System.out.println(“最小年龄:” + ageStatistics.getMin());System.out.println(“年龄总和:” + ageStatistics.getSum());System.out.println(“平均年龄:” + ageStatistics.getAverage());System.out.println(“员工总数:” + ageStatistics.getCount());//最高薪资BigDecimal maxSalary = userList.stream().map(User::getSalary).max((x1, x2) -> x1.compareTo(x2)).get();//最低薪资BigDecimal minSalary = userList.stream().map(User::getSalary).min((x1, x2) -> x1.compareTo(x2)).get();//薪资总和BigDecimal sumSalary = userList.stream().map(User::getSalary).reduce(BigDecimal.ZERO, BigDecimal::add);//平均薪资BigDecimal avgSalary = userList.stream().map(User::getSalary).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(userList.size()), 2, BigDecimal.ROUND_HALF_UP);//打印统计结果System.out.println(“最高薪资:” + maxSalary + “元”);System.out.println(“最低薪资:” + minSalary + “元”);System.out.println(“薪资总和:” + sumSalary + “元”);System.out.println(“平均薪资:” + avgSalary + “元”
//升序
userList = userList.stream().sorted(Comparator.comparingInt(User::getAge)).collect(Collectors.toList());
//降序
userList = userList.stream().sorted(Comparator.comparingInt(User::getAge).reversed()).collect(Collectors.toList());
//根据部门和性别对用户列表进行分组
Map<String,Map<String,List>> userMap = userList.stream()
.collect(Collectors.groupingBy(User::getDepartment,Collectors.groupingBy(User::getSex)));
//遍历分组后的结果userMap.forEach((key1, map) -> { System.out.println(key1 + “:”); map.forEach((key2,user)-> { System.out.println(key2 + “:”); user.forEach(System.out::println); }); System.out.println("--------------------------------------------------------------------------");});

//根据部门进行分组,汇总各个部门用户的平均年龄
Map<String, Double> userMap = userList.stream().collect(Collectors.groupingBy(User::getDepartment, Collectors.averagingInt(User::getAge)));
//遍历分组后的结果userMap.forEach((key, value) -> { System.out.println(key + “的平均年龄:” + value);});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值