Java8---Stream-系统学习

1、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
package java8.stream;
 
import java.util.*;
import java.util.stream.Stream;
 
public class GetStreamTest {
 
    public static void main(String[] args) {
        //1、通过java.util.Collection的方法 default Stream<E> stream()
        List<String> list= Arrays.asList("a","b","c");
        Stream<String> stream = list.stream();
 
        Set<String> set=new HashSet<>();
        Stream<String> stream1 = set.stream();
 
        Map<String,Object> map=new HashMap<>();
        Stream<String> stream2 = map.keySet().stream();
        Stream<Map.Entry<String, Object>> stream3 = map.entrySet().stream();
        Stream<Object> stream4 = map.values().stream();
 
 
        //2、通过java.util.stream.Stream的方法static<T> Stream<T> of(T... values)
        Stream<String> stream5 = Stream.of();
        Stream<String> stream6 = Stream.of("a", "b");;
        String[] ss=new String[]{"a","b"};
        Stream<String> stream7 = Stream.of(ss);
 
        //【注意】基本数据类型不能使用Stream,会将整个数据作为流处理
        int[] arr=new int[]{1,3};
        Stream<int[]> stream8 = Stream.of(arr);
    }
 
}

 2、Stream常用方法及返回值

 

 3、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
package java8.stream;
 
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
 
public class StreamUseNotice {
 
    public static void main(String[] args) {
 
        List<String> list= Arrays.asList("a","c");
 
        //1、stream只能使用一次
        Stream<String> stream = list.stream();
//        stream.count();
//        stream.count();
//        第二次使用报错:Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
 
        //2、stream非终结方法返回的stream为新的stream
//        Stream<String> stream1 = stream.filter(s -> s.equals("a"));
//        System.out.println(stream);
//        System.out.println(stream1);
        //结果:
        // java.util.stream.ReferencePipeline$Head@7ba4f24f
        //java.util.stream.ReferencePipeline$2@3b9a45b3
 
 
        //3、stream不调用终结方法,中间的不会执行
//        stream.filter(s -> {
//            System.out.println("未调用终结方法");
//           return true;
//        });
        //结果:未输出任何信息
        stream.filter(s -> {
            System.out.println("调用终结方法");
            return true;
        }).count();
        //结果:
        //调用终结方法
        //调用终结方法
    }
}

 4、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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package java8.stream;
 
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.IntStream;
import java.util.stream.Stream;
 
public class StreamMethodTest {
 
    public static void main(String[] args) {
//        testForEach();
//        testCount();
//        testFilter();
//        testLimit();
//        testSkip();
//        testMap();
//        testSort();
//        testDistinct();
//        testMatch();
//        testFind();
//        testMax_Min();
//        testReduce();
//        testMap_Reduce();
//        testMapToInt();
        testConcat();
    }
 
    /**
     * 将多个流 合并 为一个流
     */
    private static void testConcat() {
        Stream<String> stringStream = Stream.of("a");
        Stream<Integer> integerStream = Stream.of(1, 2);
        Stream<? extends Serializable> concatStream = Stream.concat(stringStream, integerStream);
        concatStream.forEach(a->System.out.println(a));
 
        //【注意】:合并后,之前的流不能再进行操作
    }
 
    /**
     * 将Integer流转换为 int流,减少内存空间,装箱拆箱操作
     */
    private static void testMapToInt() {
        Stream<Integer> integerStream = Stream.of(1, 3, 4);
        IntStream intStream = integerStream.mapToInt(a -> {
            return a.intValue();
        });
    }
 
    private static void testMap_Reduce() {
        //得到所有人年龄总和
        Optional<Integer> reduceSum = Stream.of(new Person("jack", 12), new Person("jack1", 13), new Person("jack3", 19)).map(a -> a.getAge()).reduce((x, y) -> x + y);
        System.out.println(reduceSum.get());
        //获取最大的年龄
        Optional<Integer> reduceMax = Stream.of(new Person("jack", 12), new Person("jack1", 13), new Person("jack3", 19)).map(a -> a.getAge()).reduce((x, y) -> x > y ? x:y);
        System.out.println(reduceMax.get());
        //统计a出现的次数
        Integer countA = Stream.of("a", "b", "a").map(s -> {
            if (s.equals("a")) {
                return 1;
            } else {
                return 0;
            }
        }).reduce((x, y) -> x + y).get();
        System.out.println(countA);
    }
 
    /**
     * 对流中的元素进行 处理,最终返回一个结果
     */
    private static void testReduce() {
         //T reduce(T identity, BinaryOperator<T> accumulator);
        //identity:默认值、accumulator:流中元素处理逻辑
//        Integer reduce = Stream.of(1, 3, 2, 4).reduce(0, (a, b) -> {
//            return a + b;
//        });
        //简化后
        Integer reduce = Stream.of(1, 3, 2, 4).reduce(0, (a, b) -> a + b);
        System.out.println(reduce);
        //获取最大值
        Integer reduceMax = Stream.of(1, 3, 2, 4).reduce(0, (a, b) -> a > b ? a : b);
        System.out.println(reduceMax);
    }
 
    /**
     * 找 流中的最大值、最小值
     */
    private static void testMax_Min() {
        Optional<Integer> max = Stream.of(1, 3, 4).max((a, b) -> {
            return a.compareTo(b);
        });
        System.out.println(max.get());
        //简化后
        System.out.println(Stream.of(1, 3, 4).max((a,b)->a.compareTo(b)).get());
 
    }
 
    /**
     * 查找流中的第一个元素  findFirst,findAny都是找第一个元素
     */
    private static void testFind() {
        Stream<Integer> stream = Stream.of(1, 3, 4);
//        Optional<Integer> first = stream.findFirst();
//        System.out.println(first.get());
        Optional<Integer> any = stream.findAny();
        System.out.println(any.get());
    }
 
    /**
     * 流中的元素是否满足某个条件
     */
    private static void testMatch() {
        Stream<Integer> stream = Stream.of(1, 3, 4);
        boolean allMatch = stream.allMatch(a -> a > 1);//流中所有元素均满足某个条件
        boolean anyMatch = stream.anyMatch(a -> a > 2);//流中任意一个元素满足某个条件
        boolean noneMatch = stream.noneMatch(a -> a < 0);//流中所有元素不满足某个条件
    }
 
    /**
     * 对流中的元素 去重
     */
    private static void testDistinct() {
        //基本类型
        Stream<Integer> stream = Stream.of(1, 2, 3, 1, 2, 3);
        stream.distinct().forEach(a->System.out.println(a));
        //String类型
        Stream<String> stream1 = Stream.of("a", "b", "c", "c", "c");
        stream1.distinct().forEach(a->System.out.println(a));
        //自定义类型
        Stream<Person> stream2 = Stream.of(new Person("jack", 12), new Person("jack", 12), new Person("rose", 12), new Person("jack", 12));
        stream2.distinct().forEach(a->System.out.println(a));
    }
 
 
 
    /**
     * 对流中元素进行排序|自定义排序
     */
    private static void testSort() {
        Stream<Integer> stream = Stream.of(1, 3, 2, 5);
//        stream.sorted().forEach(a->System.out.println(a));
//        stream.sorted((a,b)->{
//            return b.compareTo(a);
//        }).forEach(a->System.out.println(a));
        //优化后
        stream.sorted((a,b)->b.compareTo(a)).forEach(a->System.out.println(a));
    }
 
    /**
     * 将一种类型的流  转换成  另一种类型的流
     */
    private static void testMap() {
        List<String> list=new ArrayList<>();
        Collections.addAll(list,"1","2");
        Stream<Integer> stream = list.stream().map((String s) -> {
            return Integer.parseInt(s);
        });
        stream.forEach(s->System.out.println(s));
        //简化后
        list.stream().map(s->Integer.parseInt(s)).forEach(s->System.out.println(s));
    }
 
    /**
     * 跳过流中的前几位元素
     */
    private static void testSkip() {
        List<String> list=new ArrayList<>();
        Collections.addAll(list,"a","b","c","d");
        list.stream().skip(2).forEach(s->System.out.println(s));
    }
 
    /**
     * 取流中的前几位元素
     */
    private static void testLimit() {
        List<String> list=new ArrayList<>();
        Collections.addAll(list,"a","b");
        list.stream().limit(1).forEach(s->System.out.println(s));
    }
 
    /**
     * 过滤流中的数据
     */
    private static void testFilter() {
        List<String> list=new ArrayList<>();
        Collections.addAll(list,"a","b");
        list.stream().filter((String s)->{
               return s.equals("a");
        }).forEach((String s)->System.out.println(s));
        //简化后
        list.stream().filter(s->s.equals("a")).forEach(s->System.out.println(s));
    }
 
    /**
     * 统计流中的数量
     */
    private static void testCount() {
        List<String> list=new ArrayList<>();
        Collections.addAll(list,"a","b");
        //简化后
        long count = list.stream().count();
        System.out.println(count);
 
    }
 
    /**
     * 遍历流中的元素
     */
    private static void testForEach() {
        List<String> list=new ArrayList<>();
        Collections.addAll(list,"a","b");
        //
        list.stream().forEach((String s)->{
            System.out.println(s);
        });
        //简化后
        list.stream().forEach( s-> System.out.println(s));
    }
 
}

 

posted on   anpeiyong  阅读(114)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)

导航

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5
点击右上角即可分享
微信分享提示