跳至主要內容

java8之stream

知识库编程技巧JavaJava大约 5 分钟

Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作

创建方法

// 将数组转成流
Stream<Integer> stream = Arrays.stream(new Integer[10]);
// 静态方法 of
Stream<Integer> stream = Stream.of(1,2,3,4,5,6);
// 生成有序流 `0 2 4 6 8 10`
Stream<Integer> stream = Stream.iterate(0, (x) -> x + 2).limit(6);
// 生成随机流
Stream<Double> stream = Stream.generate(Math::random).limit(2);
//获取一个顺序流
Stream<String> stream = new ArrayList<>().stream();
//获取一个并行流
Stream<String> stream = new ArrayList<>().parallelStream();
// 将文件每行内容转成流
BufferedReader reader = new BufferedReader(new FileReader("F:\\test_stream.txt"));
Stream<String> lineStream = reader.lines();
lineStream.forEach(System.out::println);
// 将字符串分隔成流
Stream<String> stringStream = Pattern.compile(",").splitAsStream("a,b,c,d");
stringStream.forEach(System.out::println);

中间转换

Stream<Integer> stream = Stream.of(6, 4, 6, 7, 3, 9, 8, 10, 12, 14, 14);
Stream<Integer> newStream = stream.filter(s -> s > 5)   //过滤  6 6 7 9 8 10 12 14 14
                                  .distinct()           //去重  6 7 9 8 10 12 14
                                  .skip(2)              //跳过  9 8 10 12 14
                                  .limit(2);            //获取n个元素 9 8

List<String> list = Arrays.asList("a,b,c", "1,2,3");
// map     接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
Stream<String> s1 = list.stream().map(s -> s.replaceAll(",", ""));            // abc  123
// flatMap 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
Stream<String> s3 = list.stream().flatMap(s -> Arrays.stream(s.split(",")));  // a b c 1 2 3

消费

  • peek:如同于 map,能得到流中的每一个元素。但 map 接收的是一个 Function 表达式,有返回值;而 peek 接收的是 Consumer 表达式,没有返回值。
Student s1 = new Student("aa", 10);
Student s2 = new Student("bb", 20);
List<Student> studentList = Arrays.asList(s1, s2);
studentList.stream().peek(o -> o.setAge(100)).forEach(System.out::println);
//结果:
Student{name='aa', age=100}
Student{name='bb', age=100}

去重

// List转Map
Map<String, String> collect = list.stream().collect(Collectors.toMap(p -> p.getId(), p -> p.getName(), (a, b)-> a));
// 提取出list对象中的一个属性
List<String> stIdList1 = stuList.stream().map(Person::getId).collect(Collectors.toList());
// 提取出list对象中的一个属性并去重
List<String> stIdList2 = stuList.stream().map(Person::getId).distinct().collect(Collectors.toList());

// 根据name去重
List<Person> unique = persons.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new));
// 根据name,sex两个属性去重
List<Person> unique = persons.stream().collect(Collectors. collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + ";" + o.getSex()))), ArrayList::new));

排序

List<String> list = Arrays.asList("aa", "ff", "dd");
//String 类自身已实现Compareable接口
list.stream().sorted().forEach(System.out::println);  // aa dd ff

Student s1 = new Student("aa", 10);
Student s2 = new Student("bb", 20);
Student s3 = new Student("aa", 30);
Student s4 = new Student("dd", 40);
List<Student> studentList = Arrays.asList(s1, s2, s3, s4);

//自定义排序:先按姓名升序,姓名相同则按年龄升序
studentList.stream().sorted((o1, o2) -> {
    if (o1.getName().equals(o2.getName())) {
        return o1.getAge() - o2.getAge();
    } else {
        return o1.getName().compareTo(o2.getName());
    }
}).forEach(System.out::println);

匹配、断言

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
// 当流中每个元素都符合该断言时才返回true,否则返回false
boolean allMatch = list.stream().allMatch(e -> e > 10);   // false
// 当流中每个元素都不符合该断言时才返回true,否则返回false
boolean noneMatch = list.stream().noneMatch(e -> e > 10); // true
// 只要流中有一个元素满足该断言则返回true,否则返回false
boolean anyMatch = list.stream().anyMatch(e -> e > 4);    // true

// 返回流中第一个元素
Integer findFirst = list.stream().findFirst().get();      // 1
// 返回流中的任意元素
Integer findAny = list.stream().findAny().get();          // 1
// 返回流中元素的总个数
long count = list.stream().count();                       // 5
// 返回流中元素最大值
Integer max = list.stream().max(Integer::compareTo).get(); // 5
// 返回流中元素最小值
Integer min = list.stream().min(Integer::compareTo).get(); // 1

规约操作

//经过测试,当元素个数小于24时,并行时线程数等于元素个数,当大于等于24时,并行时线程数为16
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24);

Integer v = list.stream().reduce((x1, x2) -> x1 + x2).get();
System.out.println(v);   // 300

Integer v1 = list.stream().reduce(10, (x1, x2) -> x1 + x2);
System.out.println(v1);  //310

Integer v2 = list.stream().reduce(0,
        (x1, x2) -> {
            System.out.println("stream accumulator: x1:" + x1 + "  x2:" + x2);
            return x1 - x2;
        },
        (x1, x2) -> {
            System.out.println("stream combiner: x1:" + x1 + "  x2:" + x2);
            return x1 * x2;
        });
System.out.println(v2); // -300

Integer v3 = list.parallelStream().reduce(0,
        (x1, x2) -> {
            System.out.println("parallelStream accumulator: x1:" + x1 + "  x2:" + x2);
            return x1 - x2;
        },
        (x1, x2) -> {
            System.out.println("parallelStream combiner: x1:" + x1 + "  x2:" + x2);
            return x1 * x2;
        });
System.out.println(v3); //197474048

收集操作

Student s1 = new Student("aa", 10,1);
Student s2 = new Student("bb", 20,2);
Student s3 = new Student("cc", 10,3);
List<Student> list = Arrays.asList(s1, s2, s3);

// 转成list
List<Integer> ageList = list.stream().map(Student::getAge).collect(Collectors.toList()); // [10, 20, 10]
// 转成set
Set<Integer> ageSet = list.stream().map(Student::getAge).collect(Collectors.toSet()); // [20, 10]

// 转成map,注:key不能相同,否则报错
Map<String, Integer> studentMap = list.stream().collect(Collectors.toMap(Student::getName, Student::getAge, (a, b)-> a)); // {cc:10, bb:20, aa:10}

// 字符串分隔符连接
String joinName = list.stream().map(Student::getName).collect(Collectors.joining(",", "(", ")")); // (aa,bb,cc)

// 聚合操作
//1.学生总数
Long count = list.stream().collect(Collectors.counting()); // 3
//2.最大年龄 (最小的minBy同理)
Integer maxAge = list.stream().map(Student::getAge).collect(Collectors.maxBy(Integer::compare)).get(); // 20
//3.所有人的年龄
Integer sumAge = list.stream().collect(Collectors.summingInt(Student::getAge)); // 40
//4.平均年龄
Double averageAge = list.stream().collect(Collectors.averagingDouble(Student::getAge)); // 13.333333333333334
// 带上以上所有方法
DoubleSummaryStatistics statistics = list.stream().collect(Collectors.summarizingDouble(Student::getAge));
System.out.println("count:" + statistics.getCount() + ",max:" + statistics.getMax() + ",sum:" + statistics.getSum() + ",average:" + statistics.getAverage());

// 分组
Map<Integer, List<Student>> ageMap = list.stream().collect(Collectors.groupingBy(Student::getAge));
// 多重分组,先根据类型分再根据年龄分
Map<Integer, Map<Integer, List<Student>>> typeAgeMap = list.stream().collect(Collectors.groupingBy(Student::getType, Collectors.groupingBy(Student::getAge)));

// 分区
// 分成两部分,一部分大于10岁,一部分小于等于10岁
Map<Boolean, List<Student>> partMap = list.stream().collect(Collectors.partitioningBy(v -> v.getAge() > 10));

// 规约
Integer allAge = list.stream().map(Student::getAge).collect(Collectors.reducing(Integer::sum)).get(); //40