其他分享
首页 > 其他分享> > Stream流的收集操作

Stream流的收集操作

作者:互联网

 1 package LambdaTest.LambdaTest06;
 2 
 3 import java.util.*;
 4 import java.util.stream.Collectors;
 5 import java.util.stream.Stream;
 6 
 7 /**
 8  * FileName: StreamEndedDemo
 9  * Author:   lps
10  * Date:     2022/4/10 14:00
11  * Sign:刘品水 Q:1944900433
12  * <p>
13  * <R,A> R collect(Collector<? super T,A,R> collector)
14  * 执行 mutable reduction操作对元素的使用 Collector流。
15  * <R> R collect(Supplier<R> supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner)
16  * 执行该流的元素 mutable reduction操
17  */
18 public class StreamEndedDemo {
19     public static void main(String[] args) {
20         List<String> list = new ArrayList<>();
21         list.add("刘品水");
22         list.add("张伟");
23         list.add("刘强军");
24         list.add("朱迁民");
25 
26         //得到名字为三个字的流
27         Stream<String> threelist = list.stream().filter(s -> s.length() == 3);
28         //把此数据收集到list中遍历
29         List<String> names = threelist.collect(Collectors.toList());
30         for (String name : names) {
31             System.out.println(name);
32         }
33         System.out.println("=======");
34 
35         HashSet<Integer> set1 = new HashSet<>();
36         set1.add(10);
37         set1.add(12);
38         set1.add(20);
39         set1.add(22);
40         set1.add(29);
41         //得到大于18的流
42         Stream<Integer> setstream = set1.stream().filter(age -> age > 18);
43         //将此数据收集到set集合并遍历
44         Set<Integer> age = setstream.collect(Collectors.toSet());
45         for (Integer a : age) {
46             System.out.println(a);
47         }
48         System.out.println("=======");
49 
50         String[] strArray = {"刘品水,21", "张伟,20", "朱迁民,22", "刘子衿,3"};
51         //得到年纪大于20的流
52         Stream<String> arraystream = Stream.of(strArray).filter(s -> Integer.parseInt(s.split(",")[1]) > 20);
53         //把上面的内容 收集到map集合当中 姓名做键 年龄做值
54         Map<String, Integer> map = arraystream.collect(Collectors.toMap(s -> s.split(",")[0],
55                 s -> Integer.parseInt(s.split(",")[1])));
56         Set<String> keyset = map.keySet();
57         for (String key : keyset) {
58             Integer value = map.get(key);
59             System.out.println(key + "," + value);
60 
61         }
62 
63 
64     }
65 }

 

标签:20,Stream,收集,list,collect,add,set1,操作
来源: https://www.cnblogs.com/lps1944900433/p/16126562.html