Java Stream的各种使用方法

针对类中某一个字段的求和操作

// BigDecimal
BigDecimal bb =list.stream().map(Plan::getAmount).reduce(BigDecimal.ZERO,BigDecimal::add);

// int、double、long:
double max = list.stream().mapToDouble(User::getHeight).sum();

通过Stream转换集合为Map

1、指定key-value,value是对象中的某个属性值


 Map<Integer,String> map = userList.stream().collect(Collectors.toMap(User::getId,User::getName));

2、指定key-value,value是对象本身,User->User 是一个返回本身的lambda表达式


Map<Integer,User> map = userList.stream().collect(Collectors.toMap(User::getId,User->User));

3、指定key-value,value是对象本身,Function.identity()是简洁写法,也是返回对象本身


 Map<Integer,User> map = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));

4、指定key-value,value是对象本身,Function.identity()是简洁写法,也是返回对象本身,key 冲突的解决办法,这里选择第二个key覆盖第一个key。

 Map<Integer,User> map = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(),(key1,key2)->key2));

Stream转换集合为map的博客参考:
link

Java8 stream 中利用 groupingBy 进行多字段分组求和

link


版权声明:本文为qq_33704186原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。