java8之Stream数据流介绍(1)

来源:互联网 发布:虾米音乐 2.0mac 编辑:程序博客网 时间:2024/04/28 03:32
 XML Code 
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
224
225
226
227
228
229
230
231
232
233
234
package com.lyzx.day02;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.IntStream;
import java.util.stream.Stream;

import org.junit.Test;

public class T6 {
    
    /**
     * Java8中有两大最为重要的改变。
     * 第一个是 Lambda 表达式;
     * 另外一个则是 Stream API(java.util.stream.*)。
     * Stream 是 Java8 中处理集合的关键抽象概念,
     * 它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。
     * 使用Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询。
     * 也可以使用 Stream API 来并行执行操作。简而言之,
     * Stream API 提供了一种高效且易于使用的处理数据的方式。
     */
    
    
    /**
     * 流(Stream) 到底是什么呢?
     * 是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。
     * “集合讲的是数据,流讲的是计算! ”
     * 
     * 注意:
     *  ①Stream 自己不会存储元素。
     *  ②Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。
     *  ③Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行
     */
    
    /**
     * 创建 Stream
     * Java8 中的 Collection 接口被扩展,提供了
     * 两个获取流的方法:
     * default Stream<E> stream() : 返回一个顺序流
     * default Stream<E> parallelStream() : 返回一个并行流
     * 
     * Collection的stream()方法
     * Arrays.stream()
     */
    
    private static List<String> data = Arrays.asList("a","b","c",
                                                     "aa","bb","cc",
                                                     "A","B","C","D",
                                                     "AA","BB","CC","DD",
                                                     "abc","bcd","edf","hij",
                                                     "AA","CC");
    @Test
    public void test1(){
        Set<String> set = new HashSet<String>();
        Stream<String> s1 = set.stream();
        
        List<String> list = new ArrayList<String>();
        Stream<String> s2 = list.stream();
        
        int[] arr = new int[10];
        IntStream s3 = Arrays.stream(arr);
        
        Stream<String> s4 = Stream.of("aa","abcdefg","123");
        
        
        //下面两种是产生无限流
        //seed种子即初始值  ,f 一元操作
        Stream<Integer> s5 = Stream.iterate(100,(x)->x+1);
        
        //产生无限个随机数
        Stream<Double> s6 = Stream.generate(()->Math.random());
        s6.forEach(System.out :: println);
    }
    
    
    /**
     * Stream流就像水流一样
     * 首先有数据源,数据由一端流向另一端
     * 在流动的过程中可以有中间操作,直到有终止操作时所有的中间操作才执行即"懒执行"
     * 所有操作都不会影响数据源,即如果有移除或者过滤操作时源数据不受影响
     * 
     * 
     * filter(Predicate p) 接收 Lambda , 从流中排除某些元素。
     */
    @Test
    public void test2(){
        data.stream()
            .filter(x->{return x.length()>2;})
            .forEach(System.out::println);
    }
    
    /**
     * distinct()筛选,通过流所生成元素的 hashCode()和 equals()去除重复元素
     */
    @Test
    public void test3(){
        data.stream()
            .distinct()
            .forEach(System.out::println);
    }
    
    /**
     * limit(long maxSize) 截断流,使其元素不超过给定数量。
     */
    @Test
    public void test4(){
        data.stream().limit(5)
        .forEach(System.out::println);
    }
    
    /**
     * skip(long n) 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n个,则返回一个空流。与 limit(n)互补
     */
    @Test
    public void test5(){
        data.stream()
        .skip(15)
        .forEach(System.out::println);
    }
    
    
    

    private static List<User> users = 
                    Arrays.asList(new User("lyh",22,135.00,18L),
                                  new User("lyzx",23,123.00,18L),
                                  new User("宇文成都",29,145.00,17L)
                              );
    
    /**
     * map(Function f) 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
     * 参数是Function类型的接口把一种类型转换为另一种类型
     */
    @Test
    public void test6(){
        users.stream()
             .map(x->x.getName())
             .forEach(System.out::println);
    }
    
    /**
     * mapToDouble(ToDoubleFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 DoubleStream。
     * mapToInt(ToIntFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 IntStream。
     * mapToLong(ToLongFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 LongStream。
     */
    @Test
    public void test7(){
        int count = users.stream()
             .mapToInt(x->x.getAge())
             .sum();
        System.out.println(count);
        
        users.stream()
             .filter(x->x.getName().length()>3)
             .forEach(System.out::println);
    }
    
    
    /**
     * flatMap(Function f) 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
     */
    List<String> worlds = 
            Arrays.asList("hello welcome""world hello",
                          "hello world""hello world welcome");  

    @Test
    public void test8(){
                worlds.stream()
                .map(item ->item.split(" "))
                .forEach(x->{
                    for(String item : x){
                        System.out.println(item);
                    }
                });
    }
    
    /**
     * flatMap类似于Collection接口的addAll(Collection coll)方法
     * 可以把coll里面的东西都放在一个Collection里面
     * flatMap(item->Stream<T>) 返回流
     */
    @Test
    public void test9(){
        worlds.stream()
              .flatMap(item->{
                    String[] arr = item.split(" ");
                    return Arrays.asList(arr).stream();
                            })
              .forEach(System.out::println);
    }
}

class User{
    private String name;
    private int age;
    private double weight;
    private long size;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public double getWeight() {
        return weight;
    }
    public void setWeight(double weight) {
        this.weight = weight;
    }
    public long getSize() {
        return size;
    }
    public void setSize(long size) {
        this.size = size;
    }
    
    public User(){}
    public User(String name, int age, double weight, long size) {
        super();
        this.name = name;
        this.age = age;
        this.weight = weight;
        this.size = size;
    }
}