Java8 Stream

Java 8 API添加了一个新的抽象称为流Stream,可以让你以一种声明的方式处理数据。

Stream 使用一种类似用 SQL 语句从数据库查询数据的直观方式来提供一种对 Java 集合运算和表达的高阶抽象。

Stream API可以极大提高Java程序员的生产力,让程序员写出高效率、干净、简洁的代码。

这种风格将要处理的元素集合看作一种流, 流在管道中传输, 并且可以在管道的节点上进行处理, 比如筛选, 排序,聚合等。

元素流在管道中经过中间操作(intermediate operation)的处理,最后由最终操作(terminal operation)得到前面处理的结果。

+--------------------+       +------+   +------+   +---+   +-------+
| stream of elements +-----> |filter+-> |sorted+-> |map+-> |collect|
+--------------------+       +------+   +------+   +---+   +-------+

学习代码记录

List<Long> nums = Arrays.asList(3L, 3L, 39L, 32L, 123L, 534L, 46542L, 3211L);
nums.stream()
        .map(integer -> integer * integer + "  ")
        .distinct()
        .collect(Collectors.toList())
        .forEach(System.out::print);

System.out.println();
System.out.println("----------------------------------------------");

long count = nums.stream().filter(i -> i.equals(3L)).count();
System.out.println("包含3L的有 = " + count+"个");
System.out.println("----------------------------------------------");


Random random = new Random();
System.out.println("随机数排序前");
random.ints().limit(10).forEach(System.out::println);
System.out.println("----------------------------------------------");
System.out.println("随机数排序后");
random.ints().limit(10).sorted().forEach(System.out::println);
System.out.println("----------------------------------------------");

List<String> strings = Arrays.asList("acas", "", "sda", "sdadsaddsad", "dwadas");
long count1 = strings.parallelStream()
        .filter(s -> s.isEmpty()).count();
System.out.println("在"+strings+"中包含空字符串有" + count1 + "个");
System.out.println("----------------------------------------------");

List<String> collect = strings.stream()
        .filter(s -> !s.isEmpty())
        .collect(Collectors.toList());
System.out.println("去除空后的筛选列表"+collect);
System.out.println("----------------------------------------------");

String collect1 = strings.stream()
        .filter(s -> !s.isEmpty())
        .collect(Collectors.joining(","));
System.out.println("将"+strings+"组合成一个string后:" + collect1);
System.out.println("----------------------------------------------");

List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6, 11, 111, 22, 12);
IntSummaryStatistics intSummaryStatistics = integers.stream()
        .mapToInt((x) -> x).summaryStatistics();
System.out.println("最大值:"+intSummaryStatistics.getMax());
System.out.println("最小值:"+intSummaryStatistics.getMin());
System.out.println("所有数之和:"+intSummaryStatistics.getSum());
System.out.println("平均数:"+intSummaryStatistics.getAverage());

打印结果

9  1521  1024  15129  285156  2166157764  10310521  
----------------------------------------------
包含3L的有 = 2个
----------------------------------------------
随机数排序前
1399523865
374116917
-1454199312
1925671743
580107117
-2137427526
237695867
-55497742
-1502376427
1398197257
----------------------------------------------
随机数排序后
-2130838075
-1574466058
-1469617767
-534793213
-158077868
-143294047
234751172
1147396663
1216434490
2103427929
----------------------------------------------
在[acas, , sda, sdadsaddsad, dwadas]中包含空字符串有1个
----------------------------------------------
去除空后的筛选列表[acas, sda, sdadsaddsad, dwadas]
----------------------------------------------
将[acas, , sda, sdadsaddsad, dwadas]组合成一个string后:acas,sda,sdadsaddsad,dwadas
----------------------------------------------
最大值:111
最小值:1
所有数之和:177
平均数:17.7

Process finished with exit code 0

6.5更新

利用steam流对学生成绩进行分区

学生实体类

import lombok.Data;

@Data
public class Student {

    private String name;
    private int score;


    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }
}

处理

public static void main(String[] args) {
    List<Student> students = Arrays.asList(
            new Student("小红", 61),
            new Student("小绿", 51),
            new Student("小蓝", 60),
            new Student("小紫", 99),
            new Student("小粉", 100),
            new Student("小灰", 59)
    );
    Map<Boolean, List<Student>> collect = students.stream()
            .collect(Collectors.partitioningBy(student -> student.getScore() > 59));
    System.out.println("collect = " + collect);
    System.out.println("及格的");
    System.out.println(collect.get(true));
    System.out.println("不及格的");
    System.out.println(collect.get(false));

}

打印结果

collect = {false=[Student(name=小绿, score=51), Student(name=小灰, score=59)], true=[Student(name=小红, score=61), Student(name=小蓝, score=60), Student(name=小紫, score=99), Student(name=小粉, score=100)]}
及格的
[Student(name=小红, score=61), Student(name=小蓝, score=60), Student(name=小紫, score=99), Student(name=小粉, score=100)]
不及格的
[Student(name=小绿, score=51), Student(name=小灰, score=59)]

Process finished with exit code 0

The best preparation for tomorrow is doing your best today.