java的stream的使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
过滤
filter;
    //匹配第一个元素
        Optional<Integer> findFirst=list.stream().filter(x->x>6).findFirst();
//任意匹配  (适用于并行流)
        List<String> collect = personList.stream().filter(x -> x.getSalary() > 8000).map(Person::getName).collect(Collectors.toList());
 
 
 
 
 //任意匹配  (适用于并行流)
        Optional<Integer> findAny=list.parallelStream().filter(x->x>6).findAny();
 
 
 
 
是否匹配:
anyMatch:
        // 是否包含符合特定条件的元素
        boolean anyMatch=list.stream().anyMatch(x->x>6);
 
 
 
 
映射
map:
//        案例二:将员工的薪资全部增加1000。
        List<Person> personListNew = personList.stream().map(person -> {
            // 不改变原来员工集合的方式
            Person person1 = new Person(person.getName(), 0, null, 0, null);
            person1.setSalary(person.getSalary() + 1000);
            return person1;
        }).collect(Collectors.toList());
 
 
 List<Person> collect3 = personList.stream().map(person -> {
            // 改变原来员工集合的方式
            person.setSalary(person.getSalary() + 1000);
            return person;
        }).collect(Collectors.toList());
 
//变成大写
 String[] strArr = { "abcd", "bcdd", "defde", "fTr" };
        List<String> collect1 = Arrays.stream(strArr).map(String::toUpperCase).collect(Collectors.toList());
 
 
 
 
//                map分为两组
//                flatMap分为两一组
        //.map获取两个班级所有的男生的集合
        List<List<Person>> boyLists = gradeManageList.stream()  //返回一个list 的List<Person>
                .map(classManageMap -> classManageMap.get("男生"))
                .collect(Collectors.toList());
 
        //.flatMap获取两个班级所有男生的集合,返回一个List<Person>
        List<Person> boyList = gradeManageList.stream()   //返回Person 的list
                .flatMap(classManageMap -> classManageMap.get("男生").stream())
                .collect(Collectors.toList());
 
 
//        案例三:将两个字符数组合并成一个新的字符数组。
        List<String> list7 = Arrays.asList("m,k,l,a", "1,3,5,7");
        List<String> collect4 = list7.stream().flatMap(s -> {
            //把每个元素转化成一个stream
            String[] split = s.split(",");
            Stream<String> s2 = Arrays.stream(split);
            return s2;
        }).collect(Collectors.toList());
 
 
 
 
 
 
最大
max:
        Optional<Person> max2 = personList.stream().max(Comparator.comparing(Person::getSalary));
//        System.out.println(max2.get());
//        3.3 聚合(max/min/count)
        List<String> strings = Arrays.asList("adnm", "admmt", "pot", "xbangd", "weoujgsd");
        Optional<String> max = strings.stream().max(Comparator.comparing(String::length));
//        System.out.println("最长的字符串:" + max.get());
        Optional<Person> max1 = personList.stream().max(Comparator.comparing(Person::getAge));
//        System.out.println("最大年龄"+max1.get());
 
 
  //自然排序
        Optional<Integer> max3=list3.stream().max(Integer::compareTo);
 
 //自定义排序
        Optional<Integer> max4 = list3.stream().max(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1.compareTo(o2);
            }
        });
 
 
 
 
 
 
归纳
reduce:
// 求工资之和方式1:
        Optional<Integer> reduce1 = personList.stream().map(Person::getSalary).reduce(Integer::sum);
        // 求工资之和方式2:
        Integer reduce = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), (sum1, sum2) -> sum1 + sum2);
        // 求工资之和方式3:
        Integer reduce3 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), Integer::sum);
 
// 求最高工资方式1:
        Integer reduce2 = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(), Integer::max);
        Integer maxSalary2 = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),
                (max1, max3) -> max1 > max3 ? max1 : max3);
 
 
 
List<Integer> list8 = Arrays.asList(1, 3, 2, 8, 11, 4);
        // 求和
        Optional<Integer> sum1=list8.stream().reduce((x,y)-> x + y);
        Optional<Integer> sum2=list8.stream().reduce(Integer::sum);
        Integer sum3= list8.stream().reduce(0, Integer::sum);
 
        // 求乘积
        Optional<Integer> sum4=list8.stream().reduce((x,y)-> x * y);
 
        // 求最大值方式
        Optional<Integer> max6=list8.stream().reduce((x,y)-> x > y?x:y);
          Integer max5=list8.stream().reduce(1,Integer::max);
 
 
 
 
        Map<String, Person> collect7 = personList0.stream().filter(p -> p.getSalary() > 8000).collect(Collectors.toMap(Person::getName, p -> p));
 
    //统计员工人数
        Long collect6 = personList0.stream().collect(Collectors.counting());
   //平均工资
        Double collect8 = personList0.stream().collect(Collectors.averagingDouble(Person::getSalary));
    // 求最高工资
        Optional<Integer> collect9 = personList0.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));
 
 
   // 求工资之和
        Double collect10 = personList0.stream().collect(Collectors.summingDouble(Person::getSalary));
 
//以上总计数量,最大,最小,平均
        DoubleSummaryStatistics collect0 = personList0.stream().collect(Collectors.summarizingDouble(Person::getSalary));
 
 
 
 
接合(joining):
 String collect14 = personList0.stream().map(p -> p.getName()).collect(Collectors.joining(","));
//        System.out.println("所有员工的姓名:" + collect14);
 
 
sorted:
//        sorted,中间操作。有两种排序:
//        sorted():自然排序,流中元素需实现Comparable接口
//        sorted(Comparator com):Comparator排序器自定义排序
  // 按工资升序排序(自然排序)
 
//按照工资升序的人的姓名排序
        List<String> collect16 = personList0.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName).collect(Collectors.toList());
 
 
  // 先按工资再按年龄升序排序
        List<String> collect17 = personList0.stream().sorted(
                Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)
        ).map(Person::getName).collect(Collectors.toList());
 
 
 
 
concat
distinct:
 
      String[] arr1 = { "a", "b", "c", "d" };
        String[] arr2 = { "d", "e", "f", "g","a"};
        Stream<String> arr11 = Stream.of(arr1);
        Stream<String> arr22= Stream.of(arr2);
       // concat:合并两个流 distinct:去重
        List<String> distinct = Stream.concat(arr11, arr22).distinct().collect(Collectors.toList());
        // limit:限制从流中获得前n个数据
        List<Integer> collect19 = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList());
//        skip:跳过前n个数据
        List<Integer> collect20 = Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList());

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
public class Payment implements Serializable {
    private Integer id;
 
    private String serial;
 
    private static final long serialVersionUID = 1L;
 
    public Payment() {
        System.out.println("开始");
    }
 
    public Integer getId() {
        return id;
    }
 
    public void setId(Integer id) {
        this.id = id;
    }
 
    public String getSerial() {
        return serial;
    }
 
    public void setSerial(String serial) {
        this.serial = serial == null ? null : serial.trim();
    }
}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
   Payment payment12=null;
        Payment payment13 = Optional.ofNullable(payment12).orElse(new Payment());
        Payment payment14 = Optional.ofNullable(payment12).orElseGet(() -> new Payment());
        System.out.println(payment13);
        System.out.println(payment14);
控制台:
开始
开始
com.wangbiao.entity.Payment@6aaa5eb0
com.wangbiao.entity.Payment@3498ed
 
 
 
 
 
 
 
 
 
 
 
 
 
        Payment payment=new Payment();
        payment.setId(1);
        payment.setSerial("ssssssss");
 
//        会创建Payment
        Payment payment0 = Optional.ofNullable(payment).orElse(new Payment());
//        不会创建Payment
        Payment payment1 = Optional.ofNullable(payment).orElseGet(() -> new Payment());
 
        System.out.println(payment0);
 
        System.out.println(payment1);
        System.out.println(payment);
控制台:
 
开始
开始
com.wangbiao.entity.Payment@6aaa5eb0
com.wangbiao.entity.Payment@6aaa5eb0
com.wangbiao.entity.Payment@6aaa5eb0

 

1
2
3
orElse判断不为空也会创建对象,orElseGet则不会
orElseGet与orElse为空都会创建对象
在密集型调用时注意使用orElseGet,不然性能差异比较大

 

posted @   余生请多指教ANT  阅读(140)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示