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 <T, K> Map<K, T> list2Map(@NonNull Collection<T> 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<Person> 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 <integer>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 使用的案例源码和注释说明见: spring 最佳实践-Stream 的使用技巧
其实 stream 本质就是个语法糖,实现了很多有意思的特性,还提供了 parallelStream 这样的简单并发操作。
后续还会更新更多 java 和 Spring 的一些日常技巧,