java 8 map reduce_java8 stream 语法糖的几个使用技巧分享: list 转 map、reduce 等

分享几个平常用到的 stream 的一些技巧

先是最基本的几个

persons.stream()

.map(Person::getName)

.filter("notExist"::equals)

.findAny()

.orElse("default");

然后是 groupBy 实现的 list 转 map

这个是一个复杂但是完整的写法,其实可以简化,另外用 google 的 maps 工具类也可以实现。 详情可以看spring 最佳实践-Stream 的使用技巧

public static Map list2Map(@NonNull Collection list, @NonNull Function super T, K> keyFunc) {

return list.stream().collect(Collectors.toMap(keyFunc, Function.identity(),

(u, v) -> {

throw new IllegalStateException(String.format("Multiple entries with same key,%s=%s,%s=%s",

keyFunc.apply(u), u,

keyFunc.apply(v), v));

},

HashMap::new));

}

虽然我写了这个工具类但其实平常自己并不怎么用这个,我平常都会用 maps 工具类,但是那个无法主动去处理重复 key 的异常只能 catch。

最后是 reduce 的一些技巧

Person identity = new Person(null, null, 0, null);

List maxAge = persons.stream().collect(

Collectors.collectingAndThen(

//按性别分组

Collectors.groupingBy(Person::getSex,

//每组取年龄最大的

Collectors.reducing(identity, BinaryOperator.maxBy(Comparator.comparing(Person::getAge)))),

//合并各组的值

p -> new ArrayList<>(p.values()))

);

System.out.println(maxAge);

reduce 的说明

reduce(accumulator) :参数是一个执行双目运算的 Functional Interface,假如这个参数表示的操作为 op,stream 中的元素为 x, y, z, …,则 reduce() 执行的就是 x op y op z ...,所以要求 op 这个操作具有结合性(associative),即满足: (x op y) op z = x op (y op z),满足这个要求的操作主要有:求和、求积、求最大值、求最小值、字符串连接、集合并集和交集等。另外,该函数的返回值是 Optional 的:

Optional sum1 = numStream.reduce((x, y) -> x + y);

reduce(identity, accumulator) :可以认为第一个参数为默认值,但需要满足 identity op x = x,所以对于求和操作,identity 的值为 0,对于求积操作,identity 的值为 1。返回值类型是 stream 元素的类型:

Integer sum2 = numStream.reduce(0, Integer::sum);

reduce 如果不加参数identity则返回的是 optional 类型的,reduce 在进行双目运算时,其中一个场景是与identity做比较操作,因此我们应该满足identity op x = x

更多精彩

其实 stream 本质就是个语法糖,实现了很多有意思的特性,还提供了 parallelStream 这样的简单并发操作。

后续还会更新更多 java 和 Spring 的一些日常技巧,😁无耻嘿嘿😁 欢迎 star spring-best-practices | Github

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值