欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Java8 的特点是,使用 Stream 流,将其汇集成地图集合

最编程 2024-04-25 15:45:16
...

Java 8引入了Stream API,这是Java集合操作的一个重大改进。Stream API提供了一种高效且易于使用的处理数据的方式。

Stream是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。注意:Stream自己不会存储元素,它不会改变源对象,反而它的操作会返回一个全新的Stream,且它的操作是延迟执行的,这意味着它们会等到需要结果的时候才执行。

以下是Stream的一些常用操作:

1.Filter: 过滤Stream中的元素

java

List<String> names = Arrays.asList("John", "Peter", "Susan", "Kim", "Jen", "George", "Alan");
List<String> namesWithJ = names.stream()
                                .filter(name -> name.startsWith("J"))
                                .collect(Collectors.toList());

2.Map: 将Stream中的每一个元素映射到另一个对象上

List<String> upperCaseNames = names.stream()
                                    .map(String::toUpperCase)
                                    .collect(Collectors.toList());

3.Sorted: 对Stream中的元素进行排序

List<String> sortedNames = names.stream()
                                 .sorted()
                                 .collect(Collectors.toList());

4.Collect: 将Stream中的元素收集到一个结果容器中,如集合

List<String> nameList = names.stream().collect(Collectors.toList());

4.1将流转为map

//用stream将name转为map集合
Map<Integer, String> collect1 = Arrays.stream(names).collect(Collectors.toMap(
       s -> s.length(),
       s -> s,
       (s1, s2) -> s1 + "," + s2 //出现两个相同的key时,合并value
));
//用stream将name转为map集合,并合并相同长度的name
System.out.println(collect1);

Map<Integer, List<String>> collect = Arrays.stream(names).collect(Collectors.groupingBy(String::length));
System.out.println(collect);

5.Match: 检查Stream中的元素是否匹配给定的条件

boolean allNamesStartWithJ = names.stream().allMatch(name -> name.startsWith("J"));

6.Reduce: 使用给定的函数,将Stream中的元素累积合并成一个汇总结果

String joinedNames = names.stream().reduce("", (a, b) -> a + ", " + b);