java 8 stream 流使用总结

stream().map 集合元素转换

示例:

text
复制代码
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); List<Integer> squaredNumbers = numbers.stream() .map(n -> n * n) .collect(Collectors.toList());

作用:映射指的是对流中的每个元素应用一个函数,并将结果作为新的流中的元素。

stream().flatMap 扁平化

示例:

text
复制代码
List<List<String>> nestedList = Arrays.asList( Arrays.asList("a", "b", "c"), Arrays.asList("d", "e"), Arrays.asList("f", "g", "h", "i") ); List<String> flatList = nestedList.stream() .flatMap(childList -> childList.stream()).collect( Collectors.toList()); System.out.println(flatList);// [a, b, c, d, e, f, g, h, i]

collect(Collectors.toMap... 集合合并去重

1.方法说明

text
复制代码
Collector<T, ?, Map<K, U>> toMap(Function<? super T, ? extends K> keyMapper,Function<? super T, ? extends U> valueMapper, BinaryOperator<U> mergeFunction); keyMapper:用于将流中的元素转换为 Map 的键。 valueMapper:用于将流中的元素转换为 Map 的值。 mergeFunction 参数,用于解决键冲突的情况。当流中有两个或更多元素映射到相同的键时,mergeFunction 会被用来合并这些元素的值。

2.使用示例

text
复制代码
// 源list List<Person> people = Arrays.asList( new Person("Alice", 30), new Person("Bob", 25), new Person("Charlie", 35), new Person("Charlie", 28) ); Map<String, Integer> nameToAgeMap = people.stream() .collect(Collectors.toMap( Person::getName, // 集合key Person::getAge, // 集合value (age1, age2) -> Math.max(age1, age2) // 冲突解决 )); System.out.println(nameToAgeMap);//{Alice=30, Bob=25, Charlie=35}
0个评论
点击登录,快来和大家讨论吧~
表情
图片
暂无评论
下载 APP