Java基础

Stream API

2018-07-24  本文已影响0人  聂叼叼

一、了解Stream

Java8中有两大最为重要的改变。第一个是Lambda表达式;另外一个则是Stream API(java.util.stream.*)

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

使用Stream API对集合数据进行操作,就类似于使用sql执行的数据库查询。也可以使用Stream API来并行执行操作。简而言之,Stream API提供了一种高效且易于使用的处理数据的方式。

二、什么是Stream

流(Stream)到底是什么呢?

是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。

“集合讲的是数据,流讲的是计算!”。

注意:

(1)、Stream自己不会存储元素。

(2)、Stream不会改变源对象。相反,他们会返回一个持有结果的新Stream。

(3)、Stream操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。

三、Stream的操作三个步骤

(1)、创建Stream

一个数据源(如:集合、数组),获取一个流

(2)、中间操作

一个中间操作链,对数据源的数据进行处理

(3)、终止操作(终端操作)

一个终止操作,执行中间操作链,并产生结果。

四、创建Stream

在创建Stream前,我先来创建一个对象,供下面使用。Employee.java

package com.nieshenkuan.pojo;

public class Employee {

    private int id;
    private String name;
    private int age;
    private double salary;

    public Employee() {
    }

    public Employee(String name) {
        this.name = name;
    }
    public Employee(Integer id) {
        this.id = id;
    }
    public Employee(Integer id,Integer age) {
        this.id = id;
        this.age = age;
    }

    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Employee(int id, String name, int age, double salary) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    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 getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public String show() {
        return "测试方法引用!";
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + id;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        long temp;
        temp = Double.doubleToLongBits(salary);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Employee other = (Employee) obj;
        if (age != other.age)
            return false;
        if (id != other.id)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (Double.doubleToLongBits(salary) != Double.doubleToLongBits(other.salary))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + "]";
    }

}

创建一个测试类StreamAPI.java,,并创建一个test方法。所有的创建Stream的方式都在这个类的test方法中。

@Test
    public void test() {
        
    }
4.1、可以通过Collection系列集合提供的stream()或parallelStream()

创建代码:

// 1.1可以通过Collection系列集合提供的stream()或parallelStream()
        List<String> list = new ArrayList<>();
        Stream<String> stream1 = list.stream();
4.2、通过Arrays中的静态方法stream()获取数组流

创建代码:

// 1.2通过Arrays中的静态方法stream()获取数组流
        Employee[] emps = new Employee[10];
        Stream<Employee> stream2 = Arrays.stream(emps);
4.3、通过Stream类中的静态方法of()

创建代码:

// 1.3通过Stream类中的静态方法of()
        Stream<String> stream3 = Stream.of("aa", "bb", "cc");
        stream3.forEach(System.out::println);
4.4、创建无限流
4.4.1、迭代

创建代码:

// 1.4.1、迭代
        Stream<Integer> stream4 = Stream.iterate(0, (x) -> x + 2);
        stream4.limit(10)
               .forEach(System.out::println);
4.4.2、生成

创建代码:

// 1.4.2、生成
        Stream.generate(() -> Math.random()).limit(5)
                                         .forEach(System.out::println);

注意:

常用的是第一种跟第二种,这里面获取的都是串行流(利用Stream),还有一种就是并行流,其获取方式是parallelStream。

五、中间操作

在中间操作前,我们先在StreamAPI.java中新创建一个Employee对象的集合,然后每一个中间操作,我这里都写了一个测试类。

创建的Employee集合对象如下:

// 2. 中间操作
    List<Employee> emps = Arrays.asList(
            new Employee(102, "李四", 59, 6666.66), 
            new Employee(101, "张三", 18, 9999.99),
            new Employee(103, "王五", 28, 3333.33), 
            new Employee(104, "赵六", 8, 7777.77),
            new Employee(104, "赵六", 8, 7777.77), 
            new Employee(104, "赵六", 8, 7777.77),
            new Employee(105, "田七", 38, 5555.55)
            );

下面的中间操作会用到这个集合。

5.1、筛选与切片
5.1.1、filter——接收 Lambda , 从流中排除某些元素。

测试代码:

// (1)、filter——接收 Lambda , 从流中排除某些元素。
    @Test
    public void testFilter() {
        //这里加入了终止操作 ,不然中间操作一系列不会执行
        //中间操作只有在碰到终止操作才会执行
        emps.stream()
        .filter((e)->e.getAge()>18)
        .forEach(System.out::println);//终止操作
        
    }

注意:这里filter主要是过滤一些条件,这里的话就是把年龄小于18岁的Employee对象给过滤掉,然后用forEach给遍历一下,因为中间操作只有碰到终止操作才会执行,不然的话,看不到过滤效果。以下的操作都大部分都forEach了一下,为方便看到效果。filter用的还是很多的。

5.1.2、limit——截断流,使其元素不超过给定数量。

测试代码:

// (2)、limit——截断流,使其元素不超过给定数量。
    @Test
    public void testLimit() {
    emps.stream()
        .filter((e)->e.getAge()>8)
        .limit(4)//跟数据库中的limit有异曲同工之妙
        .forEach(System.out::println);//终止操作

    }

注意:这里我利用了上面的filter跟limit,代码意思是:过滤掉年龄小于8的,只要4条数据。这种"."式操作很有意思,就是中间操作都可以一直".",直到得到你想要的要求。

5.1.3、 skip(n) ——跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补

测试代码:

// (3)、skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
    @Test
    public void testSkip() {
    emps.stream()
        .filter((e)->e.getAge()>8)
        .skip(2)//这里可以查找filter过滤后的数据,前两个不要,要后面的,与limit相反
        .forEach(System.out::println);//终止操作
    }

注意:这里同样使用了filter中间操作,也可以不用,代码意思是:过滤掉年龄小于8岁的employee对象,然后前两个对象不要,只要后面的对象。跟limit意思相反。

5.1.4、distinct——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素

测试代码:

// (4)、distinct——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
    @Test
    public void testDistinct() {
    emps.stream()
        .distinct()//去除重复的元素,因为通过流所生成元素的 hashCode() 和 equals() 去除重复元素,所以对象要重写hashCode跟equals方法
        .forEach(System.out::println);//终止操作
    }

注意:distinct,去除重复的元素,因为通过流所生成元素的 hashCode() 和 equals() 去除重复元素,所以对象要重写hashCode跟equals方法,我在Employee对象中重写了这两个方法。

5.2、映射
5.2.1、map-接收Lambda,将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
5.2.2、flatMap-接收一个函数作为参数,将流中的每个值都转换成另一个流,然后把所有流连接成一个流

测试代码:

//  map-接收Lambda,将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
    @Test
    public void testMapAndflatMap() {
        List<String> list=Arrays.asList("aaa","bbb","ccc","ddd");
        list.stream()
        .map((str)->str.toUpperCase())//里面是Function
        .forEach(System.out::println);
        
        System.out.println("----------------------------------");
        //这里是只打印名字,map映射,根据Employee::getName返回一个name,映射成新的及结果name
        emps.stream()
        .map(Employee::getName)
        .forEach(System.out::println);
        
        System.out.println("======================================");
        
        //流中流
        Stream<Stream<Character>> stream = list.stream()
        .map(StreamAPI::filterCharacter);
        //{{a,a,a},{b,b,b}}
        //map是一个个流(这个流中有元素)加入流中
        
        stream.forEach(sm->{
            sm.forEach(System.out::println);
        });
        
        System.out.println("=============引进flatMap=============");
//      只有一个流
        Stream<Character> flatMap = list.stream()
        .flatMap(StreamAPI::filterCharacter);
        //flatMap是将一个个流中的元素加入流中
        //{a,a,a,b,b,b}
        flatMap.forEach(System.out::println);
        
    }
    /**
     * 测试map跟flatMap的区别
     * 有点跟集合中的add跟addAll方法类似
     * add是将无论是元素还是集合,整体加到其中一个集合中去[1,2,3.[2,3]]
     * addAll是将无论是元素还是集合,都是将元素加到另一个集合中去。[1,2,3,2,3]
     * @param str
     * @return
     */
    public static Stream<Character> filterCharacter(String str){
        List<Character> list=new ArrayList<>();
        for (Character character : str.toCharArray()) {
            list.add(character);
        }
        return list.stream();
    }

注意:map跟flatMap还是有区别的,map是一个个流(这个流中有元素)加入流中,flatMap是将一个个流中的元素加入流中。

5.3、排序
5.3.1、sorted()---自然排序(Comparable)
5.3.2、sorted(Comparator com)----定制排序(Comparator)

测试代码:

@Test
    public  void  testSorted() {
        List<String> list=Arrays.asList("ccc","aaa","bbb","ddd","eee");
        list.stream()
        .sorted()
        .forEach(System.out::println);
        
        System.out.println("=======定制排序=========");
        
        emps.stream()
        .sorted((x, y) -> {
            if(x.getAge() == y.getAge()){
                return x.getName().compareTo(y.getName());
            }else{
                return Integer.compare(x.getAge(), y.getAge());
            }
        }).forEach(System.out::println);
    }

六、终止操作

终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如:List,Integer,甚至是void。

在学习终止操作前,我又新建了一个Employee类,如下:Employee2.java

package com.nieshenkuan.pojo;


/**
 * 用来测试终止操作
 * @author NSK
 *
 */
public class Employee2 {

    private int id;
    private String name;
    private int age;
    private double salary;
    private Status status;

    public Employee2() {
    }

    public Employee2(String name) {
        this.name = name;
    }

    public Employee2(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Employee2(int id, String name, int age, double salary) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public Employee2(int id, String name, int age, double salary, Status status) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.salary = salary;
        this.status = status;
    }

    public Status getStatus() {
        return status;
    }

    public void setStatus(Status status) {
        this.status = status;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    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 getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public String show() {
        return "测试方法引用!";
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + id;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        long temp;
        temp = Double.doubleToLongBits(salary);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Employee2 other = (Employee2) obj;
        if (age != other.age)
            return false;
        if (id != other.id)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (Double.doubleToLongBits(salary) != Double.doubleToLongBits(other.salary))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Employee2 [id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + ", status=" + status
                + "]";
    }

    public enum Status {
        FREE, BUSY, VOCATION;
    }

}

然后创建了一个测试终止操作的类,TestShutdown.java

public class TestShutdown {
    List<Employee2> emps = Arrays.asList(
            new Employee2(102, "李四", 59, 6666.66, Status.BUSY),
            new Employee2(101, "张三", 18, 9999.99, Status.FREE),
            new Employee2(103, "王五", 28, 3333.33, Status.VOCATION),
            new Employee2(104, "赵六", 8, 7777.77, Status.BUSY),
            new Employee2(104, "赵六", 8, 7777.77, Status.FREE),
            new Employee2(104, "赵六", 8, 7777.77, Status.FREE),
            new Employee2(105, "田七", 38, 5555.55, Status.BUSY)
    );
    }

里面定义了我下面要使用的employee的集合。

6.1、查找与匹配
6.1.1、allMatch——检查是否匹配所有元素

测试代码片段,下面有总的代码:

System.out.println("==========allMatch==============");
        boolean allMatch = emps.stream()
                               .allMatch((e)->e.getStatus().equals(Status.BUSY));
        System.out.println(allMatch);
6.1.2、anyMatch——检查是否至少匹配一个元素

测试代码片段:

System.out.println("==========anyMatch==============");
        boolean anyMatch = emps.stream()
                               .anyMatch((e)->e.getAge()>10);
        System.out.println(anyMatch);
6.1.3、noneMatch——检查是否没有匹配的元素

测试代码片段:

    System.out.println("==========noneMatch==============");
        boolean noneMatch = emps.stream()
                                .noneMatch((e)->e.getStatus().equals(Status.BUSY));
        System.out.println(noneMatch);
6.1.4、findFirst——返回第一个元素

测试代码片段:

System.out.println("==========findFirst==============");
        Optional<Employee2> findFirst = emps.stream()
                                            .sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))//按照工资排序并输出第一个
                                            .findFirst();       
        System.out.println(findFirst);
6.1.5、findAny——返回当前流中的任意元素

测试代码片段:

System.out.println("==========findAny==============");
        Optional<Employee2> findAny = emps.stream()
            .filter((e)->e.getStatus().equals(Status.BUSY))
            .findAny();
        System.out.println(findAny);
6.1.6、count——返回流中元素的总个数

测试代码片段:

System.out.println("==========count==============");
        long count = emps.stream()
            .count();
        System.out.println(count);
6.1.7、max——返回流中最大值

测试代码片段:

System.out.println("==========max==============");
        Optional<Double> max = emps.stream()
            .map(Employee2::getSalary)
            .max(Double::compare);
        System.out.println(max);
6.1.8、min——返回流中最小值

测试代码片段:


        System.out.println("==========min==============");
        Optional<Employee2> min = emps.stream()
                                      .min((e1,e2)->Double.compare(e1.getSalary(), e2.getSalary()));
        System.out.println(min);

总的测试代码:

    //3. 终止操作
    /*查找与匹配
        allMatch——检查是否匹配所有元素
        anyMatch——检查是否至少匹配一个元素
        noneMatch——检查是否没有匹配的元素
        findFirst——返回第一个元素
        findAny——返回当前流中的任意元素
        count——返回流中元素的总个数
        max——返回流中最大值
        min——返回流中最小值
     */
    @Test
    public void test() {
//      emps.stream():获取串行流
//      emps.parallelStream():获取并行流
        System.out.println("==========allMatch==============");
        boolean allMatch = emps.stream()
                               .allMatch((e)->e.getStatus().equals(Status.BUSY));
        System.out.println(allMatch);
        
        System.out.println("==========anyMatch==============");
        boolean anyMatch = emps.stream()
                               .anyMatch((e)->e.getAge()>10);
        System.out.println(anyMatch);
        
        System.out.println("==========noneMatch==============");
        boolean noneMatch = emps.stream()
                                .noneMatch((e)->e.getStatus().equals(Status.BUSY));
        System.out.println(noneMatch);
        
        
        System.out.println("==========findFirst==============");
        Optional<Employee2> findFirst = emps.stream()
                                            .sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))//按照工资排序并输出第一个
                                            .findFirst();       
        System.out.println(findFirst);
        
        
        System.out.println("==========findAny==============");
        Optional<Employee2> findAny = emps.stream()
            .filter((e)->e.getStatus().equals(Status.BUSY))
            .findAny();
        System.out.println(findAny);
        
        System.out.println("==========count==============");
        long count = emps.stream()
            .count();
        System.out.println(count);
        
        
        System.out.println("==========max==============");
        Optional<Double> max = emps.stream()
            .map(Employee2::getSalary)
            .max(Double::compare);
        System.out.println(max);
        
        System.out.println("==========min==============");
        Optional<Employee2> min = emps.stream()
                                      .min((e1,e2)->Double.compare(e1.getSalary(), e2.getSalary()));
        System.out.println(min);
        
            
    }
6.2、归约
6.2.1、reduce(T identity, BinaryOperator) / reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。

测试代码:

@Test
    public void testReduce() {
        List<Integer> list= Arrays.asList(1,2,3,4,5,6,7,8,9,10);
        Integer sum = list.stream()
            .reduce(0,(x,y)->x+y);
        System.out.println(sum);
        
        Optional<Double> reduce = emps.stream()
            .map(Employee2::getSalary)
            .reduce(Double::sum);
        System.out.println(reduce.get());
        
    }
6.3、收集

Collector接口中方法的实现决定了如何对流执行收集操作(如收集到List、Set、Map)。但是Collectors实用类提供了很多静态方法,可以方便地创建常见收集器实例,具体方法与实例如下表:

6.3.1、Collectors.toList()

测试代码片段:

List<String> collect = emps.stream()
            .map(Employee2::getName)
            .collect(Collectors.toList());
        collect.forEach(System.out::println);
6.3.2、Collectors.toSet()

测试代码片段:


        Set<String> collect2 = emps.stream()
            .map(Employee2::getName)
            .collect(Collectors.toSet());
        collect2.forEach(System.out::println);
6.3.3、Collectors.toCollection(HashSet::new)

测试代码片段:

HashSet<String> collect3 = emps.stream()
            .map(Employee2::getName)
            .collect(Collectors.toCollection(HashSet::new));
        collect3.forEach(System.out::println);
6.3.4、Collectors.maxBy()

测试代码片段:


        
Optional<Double> collect = emps.stream()
            .map(Employee2::getSalary)
            .collect(Collectors.maxBy(Double::compare));
        System.out.println(collect.get());
        
        
        
        Optional<Employee2> collect2 = emps.stream()
            .collect(Collectors.maxBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
        System.out.println(collect2.get());
6.3.5、Collectors.minBy()

测试代码片段:

Optional<Double> collect4 = emps.stream()
        .map(Employee2::getSalary)
        .collect(Collectors.minBy(Double::compare));
        System.out.println(collect4);
        
        
        Optional<Employee2> collect3 = emps.stream()
        .collect(Collectors.minBy((e1,e2)->Double.compare(e1.getSalary(),e2.getSalary())));
        System.out.println(collect3.get());
6.3.6、Collectors.summingDouble()

测试代码片段:

Double collect5 = emps.stream()
        .collect(Collectors.summingDouble(Employee2::getSalary));
    System.out.println(collect5);
6.3.7、Collectors.averagingDouble()

测试代码片段:

Double collect6 = emps.stream()
    .collect(Collectors.averagingDouble((e)->e.getSalary()));
    
    Double collect7 = emps.stream()
    .collect(Collectors.averagingDouble(Employee2::getSalary));
    
    System.out.println("collect6:"+collect6);
    System.out.println("collect7:"+collect7);
6.3.8、Collectors.counting()

测试代码片段:

//总数
    Long collect8 = emps.stream()
                       .collect(Collectors.counting());
    System.out.println(collect8);
6.3.9、Collectors.summarizingDouble()

测试代码片段:

DoubleSummaryStatistics collect9 = emps.stream()
        .collect(Collectors.summarizingDouble(Employee2::getSalary));
    long count = collect9.getCount();
    double average = collect9.getAverage();
    double max = collect9.getMax();
    double min = collect9.getMin();
    double sum = collect9.getSum();
    System.out.println("count:"+count);
    System.out.println("average:"+average);
    System.out.println("max:"+max);
    System.out.println("min:"+min);
    System.out.println("sum:"+sum);
6.3.10、分组Collectors.groupingBy()

测试代码片段:

//分组
    @Test
    public void testCollect3() {
        Map<Status, List<Employee2>> collect = emps.stream()
        .collect(Collectors.groupingBy((e)->e.getStatus()));
        System.out.println(collect);
        
        
        Map<Status, List<Employee2>> collect2 = emps.stream()
            .collect(Collectors.groupingBy(Employee2::getStatus));
        System.out.println(collect2);
    }
6.3.11、多级分组Collectors.groupingBy()

测试代码片段:

//多级分组
    @Test
    public void testCollect4() {
        Map<Status, Map<String, List<Employee2>>> collect = emps.stream()
            .collect(Collectors.groupingBy(Employee2::getStatus, Collectors.groupingBy((e)->{
                if(e.getAge() >= 60)
                    return "老年";
                else if(e.getAge() >= 35)
                    return "中年";
                else
                    return "成年";
            })));
        System.out.println(collect);
    }
6.3.12、分区Collectors.partitioningBy()

测试代码片段:

//多级分组
    @Test
    public void testCollect4() {
        Map<Status, Map<String, List<Employee2>>> collect = emps.stream()
            .collect(Collectors.groupingBy(Employee2::getStatus, Collectors.groupingBy((e)->{
                if(e.getAge() >= 60)
                    return "老年";
                else if(e.getAge() >= 35)
                    return "中年";
                else
                    return "成年";
            })));
        System.out.println(collect);
    }
6.3.13、组接字符串Collectors.joining()

测试代码片段:

//组接字符串
    @Test
    public void testCollect6() {
        String collect = emps.stream()
        .map((e)->e.getName())
        .collect(Collectors.joining());
        System.out.println(collect);
        
        String collect3 = emps.stream()
        .map(Employee2::getName)
        .collect(Collectors.joining(","));
        System.out.println(collect3);
        
        
        String collect2 = emps.stream()
            .map(Employee2::getName)
            .collect(Collectors.joining(",", "prefix", "subfix"));
        System.out.println(collect2);
        
        
    }
    @Test
    public void testCollect7() {
        Optional<Double> collect = emps.stream()
        .map(Employee2::getSalary)
        .collect(Collectors.reducing(Double::sum));
        System.out.println(collect.get());
    }

测试代码片段:

    /**
     * collect——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法
     */
    @Test
    public void testCollect() {
        
        List<String> collect = emps.stream()
            .map(Employee2::getName)
            .collect(Collectors.toList());
        collect.forEach(System.out::println);
        
        
        Set<String> collect2 = emps.stream()
            .map(Employee2::getName)
            .collect(Collectors.toSet());
        collect2.forEach(System.out::println);
        
        HashSet<String> collect3 = emps.stream()
            .map(Employee2::getName)
            .collect(Collectors.toCollection(HashSet::new));
        collect3.forEach(System.out::println);
    }
    
    @Test
    public void testCollect2() {
        Optional<Double> collect = emps.stream()
            .map(Employee2::getSalary)
            .collect(Collectors.maxBy(Double::compare));
        System.out.println(collect.get());
        
        
        
        Optional<Employee2> collect2 = emps.stream()
            .collect(Collectors.maxBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
        System.out.println(collect2.get());
        
        
        Optional<Double> collect4 = emps.stream()
        .map(Employee2::getSalary)
        .collect(Collectors.minBy(Double::compare));
        System.out.println(collect4);
        
        
        Optional<Employee2> collect3 = emps.stream()
        .collect(Collectors.minBy((e1,e2)->Double.compare(e1.getSalary(),e2.getSalary())));
        System.out.println(collect3.get());
        
        
    System.out.println("=========================================");
    
    Double collect5 = emps.stream()
        .collect(Collectors.summingDouble(Employee2::getSalary));
    System.out.println(collect5);
    
    
    Double collect6 = emps.stream()
    .collect(Collectors.averagingDouble((e)->e.getSalary()));
    Double collect7 = emps.stream()
    .collect(Collectors.averagingDouble(Employee2::getSalary));
    
    System.out.println("collect6:"+collect6);
    System.out.println("collect7:"+collect7);
    
    
    //总数
    Long collect8 = emps.stream()
    .collect(Collectors.counting());
    System.out.println(collect8);
    
    
    
    DoubleSummaryStatistics collect9 = emps.stream()
        .collect(Collectors.summarizingDouble(Employee2::getSalary));
    long count = collect9.getCount();
    double average = collect9.getAverage();
    double max = collect9.getMax();
    double min = collect9.getMin();
    double sum = collect9.getSum();
    System.out.println("count:"+count);
    System.out.println("average:"+average);
    System.out.println("max:"+max);
    System.out.println("min:"+min);
    System.out.println("sum:"+sum);
    }
    
    //分组
    @Test
    public void testCollect3() {
        Map<Status, List<Employee2>> collect = emps.stream()
        .collect(Collectors.groupingBy((e)->e.getStatus()));
        System.out.println(collect);
        
        
        Map<Status, List<Employee2>> collect2 = emps.stream()
            .collect(Collectors.groupingBy(Employee2::getStatus));
        System.out.println(collect2);
    }
    //多级分组
    @Test
    public void testCollect4() {
        Map<Status, Map<String, List<Employee2>>> collect = emps.stream()
            .collect(Collectors.groupingBy(Employee2::getStatus, Collectors.groupingBy((e)->{
                if(e.getAge() >= 60)
                    return "老年";
                else if(e.getAge() >= 35)
                    return "中年";
                else
                    return "成年";
            })));
        System.out.println(collect);
    }
    //分区
    @Test
    public void testCollect5() {
        Map<Boolean, List<Employee2>> collect = emps.stream()
        .collect(Collectors.partitioningBy((e)->e.getSalary()>5000));
        System.out.println(collect);
    }
    //组接字符串
    @Test
    public void testCollect6() {
        String collect = emps.stream()
        .map((e)->e.getName())
        .collect(Collectors.joining());
        System.out.println(collect);
        
        String collect3 = emps.stream()
        .map(Employee2::getName)
        .collect(Collectors.joining(","));
        System.out.println(collect3);
        
        
        String collect2 = emps.stream()
            .map(Employee2::getName)
            .collect(Collectors.joining(",", "prefix", "subfix"));
        System.out.println(collect2);
        
        
    }
    @Test
    public void testCollect7() {
        Optional<Double> collect = emps.stream()
        .map(Employee2::getSalary)
        .collect(Collectors.reducing(Double::sum));
        System.out.println(collect.get());
    }
上一篇下一篇

猜你喜欢

热点阅读