JAVA8流操作


* Stream 的三个操作步骤:
* 1创建Stream
* 2中间操作
* 3终止操作
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
package airycode_java8.nice6;
 
import airycode_java8.nice1.Employee;
import org.junit.Test;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
 
/**
 * Stream 的三个操作步骤:
 * 1创建Stream
 * 2中间操作
 * 3终止操作
 * Created by admin on 2019/1/3.
 */
public class TestStream {
 
    @Test
    public void test1(){
        //1.通过Collection集合提供的stream()或者parallelStream()
        List<String> list = new ArrayList<>();
        Stream<String> stream1 = list.stream();
        //2.数组
        Employee[]emps = new Employee[10];
        Stream<Employee> stream2 = Arrays.stream(emps);
        //3.stream中的静态方法
        Stream.of("aa","bb","cc");
 
        //4.创建无限流
        //迭代
        Stream<Integer> stream = Stream.iterate(0, (x) -> x + 2);
        stream.limit(10).forEach(System.out::println);
 
        //生成
        Stream.generate(()->Math.random()).limit(5).forEach(System.out::println);
 
    }
 
}

  中间操作:

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
package airycode_java8.nice6;
 
import airycode_java8.nice1.Employee;
import org.junit.Test;
 
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
 
/**
 * 中间操作
 *
 * Created by admin on 2019/1/3.
 */
public class TestStreamApi2 {
 
    //准备数据
    static List<Employee> employeeList = Arrays.asList(
            new Employee("张三",18,9999.99, Employee.Status.FREE),
            new Employee("李四",38,5555.55,Employee.Status.BUSY),
            new Employee("王五",50,6666.66,Employee.Status.VOCATION),
            new Employee("赵六",16,3333.33,Employee.Status.FREE),
            new Employee("田七",8,7777.77,Employee.Status.BUSY)
    );
    /***
     * 筛选与切片
     * filter--接收Lambda,从流中排除某些元素。
     * limit--截断流,使其元素不超过给定数量
     * skip(n)--跳过元素,返回扔掉了前n个元素的流,若流中不足n个,则返回一个空流,与limit互补
     * distinct--筛选,通过流所生成的元素的hashcode和equals去除重复元素
     */
    //内部迭代:由StreamAPI提供
    @Test
    public void test1(){
        //中间操作:不会做任何的操作
        Stream<Employee> stream1 = employeeList.stream().filter((e) -> e.getAge() > 35);
        //终止操作:一次性执行全部,就是“惰性求值”
        stream1.forEach(System.out::println);
    }
 
    @Test
    public void test2(){
        //中间操作:不会做任何的操作
        Stream<Employee> stream1 = employeeList.stream().filter((e) -> e.getAge() > 35).limit(1);
        //终止操作:一次性执行全部,就是“惰性求值”
        stream1.forEach(System.out::println);
    }
 
    @Test
    public void test3(){
        //中间操作:不会做任何的操作
        Stream<Employee> stream1 = employeeList.stream().filter((e) -> e.getAge() > 35).skip(1);
        //终止操作:一次性执行全部,就是“惰性求值”
        stream1.forEach(System.out::println);
    }
 
    //去重必须重写hashcode和equals
    @Test
    public void test4(){
        //中间操作:不会做任何的操作
        Stream<Employee> stream1 = employeeList.stream().filter((e) ->e.getSalary()>5000).skip(2).distinct();
        //终止操作:一次性执行全部,就是“惰性求值”
        stream1.forEach(System.out::println);
    }
}

  中间操作2:

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
package airycode_java8.nice6;
 
import airycode_java8.nice1.Employee;
import org.junit.Test;
 
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
 
/**
 * 中间操作
 *
 * Created by admin on 2019/1/3.
 */
public class TestStreamApi3 {
 
    //准备数据
    static List<Employee> employeeList = Arrays.asList(
            new Employee("张三",18,9999.99, Employee.Status.FREE),
            new Employee("李四",38,5555.55,Employee.Status.BUSY),
            new Employee("王五",50,6666.66,Employee.Status.VOCATION),
            new Employee("赵六",16,3333.33,Employee.Status.FREE),
            new Employee("田七",8,7777.77,Employee.Status.BUSY)
    );
    /***
     * 映射
     * map--接收Lambda,将元素转换成其他形式或提取信息,接收一个函数作为参数,该函数会被应用到每一个元素上,并将其映射成一个新的元素
     * flatMap--接收一个函数作为参数,将流中的,每一个值换成另一个流,然后把所有流链接成一个流
     */
    //内部迭代:由StreamAPI提供
    @Test
    public void test1(){
        List<String> list = Arrays.asList("aaa","bbb","ccc","ddd");
        list.stream().map((str)->str.toUpperCase()).forEach(System.out::println);
        System.out.println("------------------------");
        employeeList.stream().map((employee -> employee.getName())).forEach(System.out::println);
    }
 
    //map对比flatMap
    @Test
    public void test2(){
        List<String> list = Arrays.asList("aaa","bbb","ccc","ddd");
        Stream<Stream<Character>> charStream = list.stream().map(TestStreamApi3::filterChar);
        charStream.forEach((sm)->{
            sm.forEach(System.out::println);
        });
 
 
    }
 
    //flatMap
    @Test
    public void test3(){
        List<String> list = Arrays.asList("aaa","bbb","ccc","ddd");
        list.stream().flatMap(TestStreamApi3::filterChar).forEach(System.out::println);
 
 
    }
 
    public static Stream<Character> filterChar(String str){
        List<Character> list = new ArrayList<>();
        for (Character c:str.toCharArray()) {
            list.add(c);
        }
 
        return list.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
package airycode_java8.nice6;
 
import airycode_java8.nice1.Employee;
import org.junit.Test;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
 
/**
 * 中间操作--排序
 *
 * Created by admin on 2019/1/3.
 */
public class TestStreamApi4 {
 
    //准备数据
    static List<Employee> employeeList = Arrays.asList(
            new Employee("张三",18,9999.99, Employee.Status.FREE),
            new Employee("李四",38,5555.55,Employee.Status.BUSY),
            new Employee("王五",50,6666.66,Employee.Status.VOCATION),
            new Employee("赵六",16,3333.33,Employee.Status.FREE),
            new Employee("田七",8,7777.77,Employee.Status.BUSY)
    );
    /***
     * 排序
     * sorted()-自然排序
     * sorted(Comparator com)--定制排序
     */
    @Test
    public void test1(){
        List<String> list = Arrays.asList("fff","aaa","bbb","ccc","ddd");
        list.stream().sorted().forEach(System.out::println);
        System.out.println("---------------------");
        employeeList.stream().sorted((e1,e2)->{
            if (e1.getAge() == e2.getAge()) {
                return e1.getName().compareTo(e2.getName());
            } else {
                return -Integer.compare(e1.getAge(),e2.getAge());
            }
        }).forEach(System.out::println);
    }
 
 
 
}

  终止操作:

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
package airycode_java8.nice6;
 
import airycode_java8.nice1.Employee;
import org.junit.Test;
 
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
 
/**
 * 终止操作
 *
 * Created by admin on 2019/1/3.
 */
public class TestStreamApi5 {
 
    //准备数据
    static List<Employee> employeeList = Arrays.asList(
            new Employee("张三",18,9999.99, Employee.Status.FREE),
            new Employee("李四",38,5555.55,Employee.Status.BUSY),
            new Employee("王五",50,6666.66,Employee.Status.VOCATION),
            new Employee("赵六",16,3333.33,Employee.Status.FREE),
            new Employee("田七",8,7777.77,Employee.Status.BUSY)
 
    );
    /***
     * 终止操作
     * 查找与匹配
     * allMatch--检查是否匹配所有元素
     * anyMatch--检查是否至少匹配一个元素
     * noneMatch--检查是否没有匹配所有元素
     * findFirst--返回第一个元素
     * findAny--返回当前流中的任意一个元素
     * count--返回流中元素总个数
     * max--返回流中最大值
     * min--返回流中最小值
     *
     *
     */
    @Test
    public void test1(){
        boolean allMatch = employeeList.stream().allMatch((employee -> employee.getStatus().equals(Employee.Status.BUSY)));
        System.out.println(allMatch);
 
        boolean anyMatch = employeeList.stream().anyMatch((employee -> employee.getStatus().equals(Employee.Status.BUSY)));
        System.out.println(anyMatch);
 
        boolean noneMatch = employeeList.stream().noneMatch((employee -> employee.getStatus().equals(Employee.Status.BUSY)));
        System.out.println(noneMatch);
 
        Optional<Employee> op = employeeList.stream().sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())).findFirst();
        Employee employee = op.get();
        System.out.println(employee);
 
        System.out.println("-------------------------");
        Optional<Employee> anyOp = employeeList.stream().filter((e) -> e.getStatus().equals(Employee.Status.FREE)).findAny();
        System.out.println(anyOp.get());
    }
 
    @Test
    public void test2(){
        long count = employeeList.stream().count();
        System.out.println(count);
        Optional<Employee> max = employeeList.stream().max((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
        System.out.println(max.get());
        Optional<Employee> min = employeeList.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
        System.out.println(min.get());
 
        Optional<Double> min1 = employeeList.stream().map(Employee::getSalary).min(Double::compare);
        System.out.println(min1.get());
    }
 
 
 
}

  终止操作:规约

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
package airycode_java8.nice6;
 
import airycode_java8.nice1.Employee;
import org.junit.Test;
 
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 终止操作
 *
 * Created by admin on 2019/1/3.
 */
public class TestStreamApi6 {
 
    //准备数据
    static List<Employee> employeeList = Arrays.asList(
            new Employee("张三",18,9999.99, Employee.Status.FREE),
            new Employee("李四",38,5555.55,Employee.Status.BUSY),
            new Employee("王五",50,6666.66,Employee.Status.VOCATION),
            new Employee("赵六",16,3333.33,Employee.Status.FREE),
            new Employee("田七",8,7777.77,Employee.Status.BUSY)
 
    );
    /***
     * 规约
     * reduce(T identity,BinaryOperator)--可以将流中元素反复结合起来,得到一个值
     *
     *
     */
    @Test
    public void test1(){
        List<Integer> list = Arrays.asList(1,2,3,4,5);
        Integer sum = list.stream().reduce(0, (x, y) -> x + y);
        System.out.println(sum);
        System.out.println("-----------------------");
        Optional<Double> reduceOp = employeeList.stream().map(Employee::getSalary).reduce(Double::sum);
        System.out.println(reduceOp.get());
    }
 
 
    /***
     * 收集
     * collect--将流转化为其他的形式,接收一个Collector接口的实现,用于给Stream中元素做汇总的方法
     */
 
 
    @Test
    public void test2(){
        List<String> names = employeeList.stream().map(Employee::getName).collect(Collectors.toList());
        names.forEach(System.out::println);
 
        Set<String> disNames = employeeList.stream().map(Employee::getName).collect(Collectors.toSet());
        disNames.forEach(System.out::println);
 
        System.out.println("----------------");
        HashSet<String> hashNames = employeeList.stream().map(Employee::getName).collect(Collectors.toCollection(HashSet::new));
        hashNames.forEach(System.out::println);
    }
 
 
    @Test
    public void test3(){
        //总数
        Long count = employeeList.stream().collect(Collectors.counting());
        System.out.println(count);
 
        //平均数
        Double avg = employeeList.stream().collect(Collectors.averagingDouble(Employee::getSalary));
        System.out.println(avg);
 
        //总和
        Double sum = employeeList.stream().collect(Collectors.summingDouble(Employee::getSalary));
        System.out.println(sum);
 
        //最大值员工
        Optional<Employee> employeeMax = employeeList.stream().collect(Collectors.maxBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
        System.out.println(employeeMax.get());
 
        //最小值
        Optional<Double> val = employeeList.stream().map(Employee::getSalary).collect(Collectors.minBy(Double::compare));
        System.out.println(val.get());
    }
 
 
    //分组
    @Test
    public void test4(){
        Map<Employee.Status, List<Employee>> statusListMap = employeeList.stream().collect(Collectors.groupingBy(Employee::getStatus));
        System.out.println(statusListMap);
    }
 
    //多级分组
    @Test
    public void test5(){
        Map<Employee.Status, Map<String, List<Employee>>> map = employeeList.stream().collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((employee) -> {
            if (employee.getAge() <= 35) {
                return "青年";
            } else if (employee.getAge() <= 50) {
                return "中年";
            } else {
                return "老年";
            }
        })));
        System.out.println(map);
    }
 
    //分区
    @Test
    public void test6(){
        Map<Boolean, List<Employee>> booleanListMap = employeeList.stream().collect(Collectors.partitioningBy((e) -> e.getSalary() > 8000));
 
        System.out.println(booleanListMap);
    }
 
    //获取最大值,求和,最小值,另一种方式
    @Test
    public void test7(){
        DoubleSummaryStatistics dss = employeeList.stream().collect(Collectors.summarizingDouble(Employee::getSalary));
 
        System.out.println(dss.getSum());
        System.out.println(dss.getAverage());
        System.out.println(dss.getCount());
        System.out.println(dss.getMax());
        System.out.println(dss.getMin());
    }
 
    //连接字符换
    @Test
    public void test8(){
        String str = employeeList.stream().map(Employee::getName).collect(Collectors.joining("-"));
        System.out.println(str);
    }
 
 
 
 
 
}

  

posted on   airycode  阅读(228)  评论(0编辑  收藏  举报

努力加载评论中...

导航

点击右上角即可分享
微信分享提示