Java8 新特性 Stream 之 Collectors

将流中的数据转成集合类型:


一、将数据收集进一个列表(Stream 转换为 List,允许重复值,有顺序)

1 //1.将数据收集进一个列表(Stream 转换为 List,允许重复值,有顺序)
2 //创建流
3 Stream<String> language = Stream.of("java", "python", "C++","php","java");
4 List<String> listResult = language.collect(Collectors.toList());
5 result.forEach(System.out::println);
1 //2.stream()代替流
2 List<String> list = Arrays.asList("java", "python", "C++","php","java");
3 List<String> listResult = list.stream().collect(Collectors.toList());
4 listResult.forEach(System.out::println);

输出结果为:

 

二、将数据收集进一个集合(Stream 转换为 Set,不允许重复值,没有顺序)

1 //1.将数据收集进一个集合(Stream 转换为 Set,不允许重复值,没有顺序)
2 Stream<String> language = Stream.of("java", "python", "C++","php","java");
3 Set<String> setResult = language.collect(Collectors.toSet());
4 setResult.forEach(System.out::println);

输出结果为:

 

三、用自定义的实现Collection的数据结构收集

 1 List<String> list = Arrays.asList("java", "python", "C++","php","java");
 2 //用LinkedList收集
 3 List<String> linkedListResult = list.stream().collect(Collectors.toCollection(LinkedList::new));
 4 linkedListResult.forEach(System.out::println);
 5 System.out.println("--------------");
 6 
 7 //用CopyOnWriteArrayList收集
 8 List<String> copyOnWriteArrayListResult = list.stream().collect(Collectors.toCollection(CopyOnWriteArrayList::new));
 9 copyOnWriteArrayListResult.forEach(System.out::println);
10 System.out.println("--------------");
11 
12 //用TreeSet收集
13 TreeSet<String> treeSetResult = list.stream().collect(Collectors.toCollection(TreeSet::new));
14 treeSetResult.forEach(System.out::println);

输出结果为:

 

四、对Stream的字符串拼接

1 List<String> list = Arrays.asList("java", "python", "C++","php","java");
2 //直接将输出结果拼接
3 System.out.println(list.stream().collect(Collectors.joining()));
4 //每个输出结果之间加拼接符号“|”
5 System.out.println(list.stream().collect(Collectors.joining(" | ")));
6 //输出结果开始头为Start--,结尾为--End,中间用拼接符号“||”
7 System.out.println(list.stream().collect(Collectors.joining(" || ", "Start--", "--End")));

输出结果为:

 

五、其他还有partitioningBy(),分类成一个key为True和Flase的Map。例如

1 List<String> list = Arrays.asList("java", "python", "C++","php","java");
2 Map<Boolean, List<String>> result = list.stream().collect(partitioningBy(s -> s.length() > 2));


六、collectingAndThen(),收集之后继续做一些处理。例如

1 List<String> list = Arrays.asList("java", "python", "C++","php","java");
2 //收集后转换为不可变List
3 ImmutableList<String> collect = list.stream().collect(Collectors.collectingAndThen(Collectors.toList(), ImmutableList::copyOf));


总结:

  


参考资料:

菜鸟驿站,《On Java8

 技术交流 QQ 群:816425449

 

posted @ 2021-04-28 21:03  周未没信号  阅读(359)  评论(0编辑  收藏  举报