java8新特性:lambda表达式+Stream流

记忆总结:
函数式接口:
    - 四大核心:Consumer<T>; Supplier<T>; Function<T,R>; Predicate<T>
    - 常用:Runnable; Iterable<T>; Comparator<T>; Comparable<T>
Lambda表达式:
    - 无参无返
    - 有参无返
    - 一参有返
    - 类型推断
    - 省略小括号
    - 多条语句
    - 省略return
方法引用:
    - 对象 :: 实例方法名
    - 类 :: 静态方法名
    - 类 :: 实例方法名
构造器引用:类名::new
数组构造引用:数组类型名::new
Stream API
    - 创建:集合.stream(); 数组.stream; Stream.of(... values)
    - 中间操作:
        - 筛选与切片:filter(Predicate p); limit(n); skip(n); distinct()
        - 映射:map(Function f)
        - 排序:sorted()——自然排序; sorted(Comparator com)——定制排序
    - 终止操作:
        - 匹配与查找:
            - allMatch(Predicate p);anyMatch(Predicate p);findFirst();
            - count();max(Comparator c);min(Comparator c);forEach(Consumer c)
        - 规约:reduce(T identity, BinaryOperator)
        - 收集:collect(Collector c)
            - collect(Collectors.toList()) ---> toList()
            - collect(Collectors.toSet()) ---> toSet()
            - collect(Collectors.toCollection()) ---> toCollection()

函数式接口

什么是函数式接口

只包含一个抽象方法(Single Abstract Method,简称SAM)的接口,称为函数式接口。当然该接口可以包含其他非抽象方法。

你可以通过 Lambda 表达式来创建该接口的对象。(若 Lambda 表达式抛出一个受检异常(即:非运行时异常),那么该异常需要在目标接口的抽象方法上进行声明)。

我们可以在一个接口上使用 @FunctionalInterface 注解,这样做可以检查它是否是一个函数式接口。同时 javadoc 也会包含一条声明,说明这个接口是一个函数式接口。

java.util.function包下定义了Java 8 的丰富的函数式接口

在Java8中,Lambda表达式就是一个函数式接口的实例。这就是Lambda表达式和函数式接口的关系。也就是说,只要一个对象是函数式接口的实例,那么该对象就可以用Lambda表达式来表示

四大核心函数式接口

函数式接口 称谓 参数类型 用途
Consumer<T> 消费型接口 T 对类型为T的对象应用操作,包含方法: void accept(T t)
Supplier<T> 供给型接口 返回类型为T的对象,包含方法:T get()
Function<T, R> 函数型接口 T 对类型为T的对象应用操作,并返回结果。结果是R类型的对象。包含方法:R apply(T t)
Predicate<T> 判断型接口 T 确定类型为T的对象是否满足某约束,并返回 boolean 值。包含方法:boolean test(T t)

在这四个接口的基础上,慢慢发展其他接口。

// 输入一个参数,没返回值
@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
}
// 不输入一个参数,得到返回值
@FunctionalInterface
public interface Supplier<T> {
    T get();
}

// 输入参数T;得到R
@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);
}

// 输入T,判断对错
@FunctionalInterface
public interface Predicate<T> {
    boolean test(T t);
}

其他常用的函数式接口


@FunctionalInterface
public interface Runnable {
    public abstract void run();
}
public interface Iterable<T> {
    Iterator<T> iterator();
}

@FunctionalInterface
public interface Comparator<T> {
    int compare(T o1, T o2);
}

public interface Comparable<T> {
    public int compareTo(T o);
}

Lambda表达式

Lambda表达式的作用:减少冗余的匿名内部类(函数式接口)

无参无返回值

语法格式一:无参,无返回值

    @Test
    public void test1(){
        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                System.out.println("我爱北京天安门");
            }
        };
        r1.run();

        System.out.println("***********************");
      
        //Lambda表达式的写法
        Runnable r2 = () -> {
            System.out.println("我爱上海东方明珠");
        };
        r2.run();
    }

一参无返回值

语法格式二:Lambda 需要一个参数,但是没有返回值。

@Test
public void test2(){
    //未使用Lambda表达式
    Consumer<String> con = new Consumer<String>() {
        @Override
        public void accept(String s) {
            System.out.println(s);
        }
    };
    con.accept("谎言和誓言的区别是什么?");

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

    //使用Lambda表达式
    Consumer<String> con1 = (String s) -> {
        System.out.println(s);
    };
    con1.accept("一个是听得人当真了,一个是说的人当真了");
}

类型推断

语法格式三:数据类型可以省略,因为可由编译器推断得出,称为“类型推断

类型推断的原则:没有歧义

@Test
public void test3(){
    //语法格式三使用前
    Consumer<String> con1 = (String s) -> {
        System.out.println(s);
    };
    con1.accept("一个是听得人当真了,一个是说的人当真了");

    System.out.println("*******************");
    //语法格式三使用后
    Consumer<String> con2 = (s) -> {
        System.out.println(s);// 因为只有这个方法用到了s,就能推断s是String类型
    };
    con2.accept("一个是听得人当真了,一个是说的人当真了");
}

省略小括号

语法格式四:Lambda 若只需要一个参数时,参数的小括号可以省略

@Test
public void test4(){
    //语法格式四使用前
    Consumer<String> con1 = (s) -> {
        System.out.println(s);
    };
    con1.accept("一个是听得人当真了,一个是说的人当真了");

    System.out.println("*******************");
    //语法格式四使用后
    Consumer<String> con2 = s -> {
        System.out.println(s);
    };
    con2.accept("一个是听得人当真了,一个是说的人当真了");
}

多条语句

语法格式五:Lambda 需要两个或以上的参数,多条执行语句,并且可以有返回值

@Test
public void test5(){
    //语法格式五使用前
    Comparator<Integer> com1 = new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            System.out.println(o1);
            System.out.println(o2);
            return o1.compareTo(o2);
        }
    };
    System.out.println(com1.compare(12,21));
    System.out.println("*****************************");
    //语法格式五使用后
    Comparator<Integer> com2 = (o1,o2) -> {
        System.out.println(o1);
        System.out.println(o2);
        return o1.compareTo(o2);
    };
    System.out.println(com2.compare(12,6));
}

省略return

语法格式六:当 Lambda 体只有一条语句时,return 与大括号若有,都可以省略

@Test
public void test6(){
    //语法格式六使用前
    Comparator<Integer> com1 = (o1,o2) -> {
        return o1.compareTo(o2);
    };
    System.out.println(com1.compare(12,6));
    System.out.println("*****************************");
    //语法格式六使用后
    Comparator<Integer> com2 = (o1,o2) -> o1.compareTo(o2);
    System.out.println(com2.compare(12,21));
}

@Test
public void test7(){
    //语法格式六使用前
    Consumer<String> con1 = s -> {
        System.out.println(s);
    };
    con1.accept("一个是听得人当真了,一个是说的人当真了");

    System.out.println("*****************************");
    //语法格式六使用后
    Consumer<String> con2 = s -> System.out.println(s);

    con2.accept("一个是听得人当真了,一个是说的人当真了");

}

方法引用与构造器引用

Lambda表达式是可以简化函数式接口的变量或形参赋值的语法。而方法引用和构造器引用是为了简化Lambda表达式的

方法引用

要求

Lambda体只有一句语句,并且是通过调用一个对象的方法或者类现有的方法来完成的

对象 :: 实例方法名

函数式接口中的抽象方法a在被重写时使用了某一个对象的方法b。如果方法a的形参列表、返回值类型与方法b的形参列表、返回值类型都相同,则我们可以使用方法b实现对方法a的重写、替换。

// 情况一:对象 :: 实例方法
//Consumer中的void accept(T t)
//PrintStream中的void println(T t)
@Test
public void test1() {
  //1.
  Consumer<String> con1 = new Consumer<String>() {
    @Override
    public void accept(String s) {
      System.out.println(s);
    }
  };

  con1.accept("hello!");

  //2. lambda表达式
  Consumer<String> con2 = s -> System.out.println(s);
  con2.accept("hello!");

  //3. 方法引用
  PrintStream ps = System.out;
  Consumer<String> con3 = ps :: println;
  con3.accept("hello!");

}

//Supplier中的T get()
//Employee中的String getName()
@Test
public void test2() {
  Employee emp = new Employee(1001, "马化腾", 34, 6000.38);
  //1.
  Supplier<String> sup1 = new Supplier<String>() {
    @Override
    public String get() {
      return emp.getName();
    }
  };

  System.out.println(sup1.get());

  //2. lambda表达式
  Supplier<String> sup2 = () -> emp.getName();
  System.out.println(sup2.get());

  //3. 方法引用
  Supplier<String> sup3 = emp::getName;
}

类 :: 静态方法名

函数式接口中的抽象方法a在被重写时使用了某一个类的静态方法b。如果方法a的形参列表、返回值类型与方法b的形参列表、返回值类型都相同,则我们可以使用方法b实现对方法a的重写、替换。

// 情况二:类 :: 静态方法
//Comparator中的int compare(T t1,T t2)
//Integer中的int compare(T t1,T t2)
@Test
public void test3() {
  //1
  Comparator<Integer> com1 = new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
      return Integer.compare(o1,o2);
    }
  };
  System.out.println(com1.compare(12, 21));

  //2.
  Comparator<Integer> com2 = (o1,o2) -> Integer.compare(o1,o2);
  System.out.println(com2.compare(21, 34));

  //3. 方法引用
  Comparator<Integer> com3 = Integer :: compare;
  System.out.println(com3.compare(34, 34));
}

//Function中的R apply(T t)
//Math中的Long round(Double d)
@Test
public void test4() {
  //1.
  Function<Double,Long> fun1 = new Function<Double, Long>() {
    @Override
    public Long apply(Double aDouble) {
      return Math.round(aDouble);
    }
  };
  //2.
  Function<Double,Long> fun2 = aDouble -> Math.round(aDouble);

  //3.方法引用
  Function<Double,Long> fun3 = Math :: round;

}

类 :: 实例方法名

函数式接口中的抽象方法a在被重写时使用了某一个对象的方法b。如果方法a的返回值类型与方法b的返回值类型相同,同时方法a的形参列表中有n个参数,方法b的形参列表有n-1个参数,且方法a的第1个参数作为方法b的调用者,且方法a的后n-1参数与方法b的n-1参数匹配(类型相同或满足多态场景也可以

// 情况三:类 :: 实例方法 (难)
// Comparator中的int comapre(T t1,T t2)
// String中的int t1.compareTo(t2)
@Test
public void test5() {
  //1.
  Comparator<String> com1 = new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
      return o1.compareTo(o2);
    }
  };

  System.out.println(com1.compare("abc", "abd"));

  //2.
  Comparator<String> com2 = (s1,s2) -> s1.compareTo(s2);
  System.out.println(com2.compare("abc", "abb"));

  //3.
  Comparator<String> com3 = String :: compareTo;
  System.out.println(com3.compare("abc","abb"));
}

//BiPredicate中的boolean test(T t1, T t2);
//String中的boolean t1.equals(t2)
@Test
public void test6() {
  //1.
  BiPredicate<String,String> biPre1 = new BiPredicate<String, String>() {
    @Override
    public boolean test(String s1, String s2) {
      return s1.equals(s2);
    }
  };

  //2.
  BiPredicate<String,String> biPre2 = (s1,s2) -> s1.equals(s2);

  //3. 方法引用
  BiPredicate<String,String> biPre3 = String :: equals;

}

// Function中的R apply(T t)
// Employee中的String getName();
@Test
public void test7() {
  Employee emp = new Employee(1001, "马化腾", 34, 6000.38);
  //1
  Function<Employee,String> fun1 = new Function<Employee, String>() {
    @Override
    public String apply(Employee employee) {
      return employee.getName();
    }
  };
  System.out.println(fun1.apply(emp));

  //2.
  Function<Employee,String> fun2 = employee -> employee.getName();
  System.out.println(fun2.apply(emp));

  //3.方法引用
  Function<Employee,String> fun3 = Employee :: getName;
  System.out.println(fun3.apply(emp));
}

在实际开发中,idea都会给出提示,能看得懂即可

构造器引用:类名::new

当Lambda表达式是创建一个对象,并且满足Lambda表达式的形参正好给创建这个对象的构造器的实参列表,就可以使用构造器引用。

@Test
public void test1(){
    //1.
    Supplier<Employee> sup1 = new Supplier<Employee>() {
        @Override
        public Employee get() {
            return new Employee();
        }
    };

    System.out.println(sup1.get());

    //2.构造器引用
    Supplier<Employee> sup2 = Employee::new; //调用的是Employee类中空参的构造器
    System.out.println(sup2.get());
}

//Function中的R apply(T t)
@Test
public void test2(){
    //1.
    Function<Integer,Employee> func1 = new Function<Integer, Employee>() {
        @Override
        public Employee apply(Integer id) {
            return new Employee(id);
        }
    };

    System.out.println(func1.apply(12));
    //2.构造器引用
  //调用的是Employee类中参数是Integer/int类型的构造器
    Function<Integer,Employee> func2 = Employee :: new; 
    System.out.println(func2.apply(11));
}

//BiFunction中的R apply(T t,U u)
@Test
public void test3(){
    //1.
    BiFunction<Integer,String,Employee> func1 = new BiFunction<Integer, String, Employee>() {
        @Override
        public Employee apply(Integer id, String name) {
            return new Employee(id,name);
        }
    };

    System.out.println(func1.apply(10, "Tom"));
    //2.//调用的是Employee类中参数是Integer/int、String类型的构造器
    BiFunction<Integer,String,Employee> func2 = Employee::new;
    System.out.println(func2.apply(11, "Tony"));
}

数组构造引用:数组类型名::new

当Lambda表达式是创建一个数组对象,并且满足Lambda表达式的形参正好给创建这个数组对象的长度,就可以数组构造引用。

//数组引用
//Function中的R apply(T t)
@Test
public void test4(){
    //1.
    Function<Integer,Employee[]> func1 = new Function<Integer, Employee[]>() {
        @Override
        public Employee[] apply(Integer length) {
            return new Employee[length];
        }
    };
    System.out.println(func1.apply(10).length);

    //2.
    Function<Integer,Employee[]> func2 = Employee[] :: new;
    System.out.println(func2.apply(20).length);
}

Stream API

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

Collection 是一种静态的内存数据结构,讲的是数据,而 Stream 是有关计算的,讲的是计算

  • Stream 自己不会存储元素。
  • Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。
  • Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。即一旦执行终止操作,就执行中间操作链,并产生结果
  • 可以没有中间操作,但一定要有终止操作
  • Stream一旦执行了终止操作,就不能再调用其它中间操作或终止操作了

Stream的操作三个步骤

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

中间操作:每次处理都会返回一个持有结果的新Stream,即中间操作的方法返回值仍然是Stream类型的对象。因此中间操作可以是个操作链,可对数据源的数据进行n次处理,但是在终结操作前,并不会真正执行。

终止操作(终端操作):终止操作的方法返回值类型就不再是Stream了,因此一旦执行终止操作,就结束整个Stream操作了。一旦执行终止操作,就执行中间操作链,最终产生结果并结束Stream。

实验数据

public class EmployeeData {
    
    public static List<Employee> getEmployees(){
        List<Employee> list = new ArrayList<>();
        
        list.add(new Employee(1001, "马化腾", 34, 6000.38));
        list.add(new Employee(1002, "马云", 2, 19876.12));
        list.add(new Employee(1003, "刘强东", 33, 3000.82));
        list.add(new Employee(1004, "雷军", 26, 7657.37));
        list.add(new Employee(1005, "李彦宏", 65, 5555.32));
        list.add(new Employee(1006, "比尔盖茨", 42, 9500.43));
        list.add(new Employee(1007, "任正非", 26, 4333.32));
        list.add(new Employee(1008, "扎克伯格", 35, 2500.32));
        
        return list;
    }
}
//--------------------------------------------------------------------
public class Employee {

    private int id;
    private String name;
    private int age;
    private double salary;
  
    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;

        Employee employee = (Employee) o;

        if (id != employee.id)
            return false;
        if (age != employee.age)
            return false;
        if (Double.compare(employee.salary, salary) != 0)
            return false;
        return name != null ? name.equals(employee.name) : employee.name == null;
    }

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

创建Stream实例

通过集合

    //创建 Stream方式一:通过集合
    @Test
    public void test1(){
        List<Employee> list = EmployeeData.getEmployees();
//        default Stream<E> stream() : 返回一个顺序流
        Stream<Employee> stream = list.stream();
//        default Stream<E> parallelStream() : 返回一个并行流
        Stream<Employee> stream1 = list.parallelStream();
        System.out.println(stream);
        System.out.println(stream1);
    }

通过数组

//创建 Stream方式二:通过数组
@Test
public void test2(){
    //调用Arrays类的static <T> Stream<T> stream(T[] array): 返回一个流
    Integer[] arr = new Integer[]{1,2,3,4,5};

    Stream<Integer> stream = Arrays.stream(arr);

    int[] arr1 = new int[]{1,2,3,4,5};
    IntStream stream1 = Arrays.stream(arr1);
}

通过Stream的of()

/**创建 Stream方式三:通过Stream的of()
  public static<T> Stream<T> of(T... values) {
    return Arrays.stream(values);
  }*/
@Test
public void test3(){
    Stream<String> stream = Stream.of("AA", "BB", "CC", "SS", "DD");
}

中间操作

筛选与切片

//1-筛选与切片
@Test
public void test1() {
//        filter(Predicate p)——接收 Lambda,从流中排除某些元素。
    //练习:查询员工表中薪资大于7000的员工信息
    List<Employee> list = EmployeeData.getEmployees();
    Stream<Employee> stream = list.stream();
      // void forEach(Consumer<? super T> action);
    stream.filter(emp -> emp.getSalary() > 7000).forEach(System.out::println);
    //Employee{id=1002, name='马云', age=2, salary=19876.12}
    //Employee{id=1004, name='雷军', age=26, salary=7657.37}
    //Employee{id=1006, name='比尔盖茨', age=42, salary=9500.43}

    System.out.println();
//        limit(n)——截断流,使其元素不超过给定数量。也就是返回前n个
    //错误的。因为stream已经执行了终止操作,就不可以再调用其它的中间操作或终止操作了。
//        stream.limit(2).forEach(System.out::println);
    list.stream().filter(emp -> emp.getSalary() > 7000).limit(2).forEach(System.out::println);
    //Employee{id=1002, name='马云', age=2, salary=19876.12}
    //Employee{id=1004, name='雷军', age=26, salary=7657.37}


    System.out.println();
//    skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
    list.stream().skip(5).forEach(System.out::println);
    //Employee{id=1006, name='比尔盖茨', age=42, salary=9500.43}
    //Employee{id=1007, name='任正非', age=26, salary=4333.32}
    //Employee{id=1008, name='扎克伯格', age=35, salary=2500.32}

    System.out.println();
//        distinct()——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
    list.add(new Employee(1009, "马斯克", 40, 12500.32));
    list.add(new Employee(1009, "马斯克", 40, 12500.32));
    list.add(new Employee(1009, "马斯克", 40, 12500.32));
    list.add(new Employee(1009, "马斯克", 40, 12500.32));

    list.stream().distinct().forEach(System.out::println);
}

映 射

//2-映射
@Test
public void test2() {
//map(Function f)——接收一个函数作为参数,将元素转换成其他形式或提取信息,
//该函数会被应用到每个元素上,并将其映射成一个新的元素。
  //练习:转换为大写
  List<String> list = Arrays.asList("aa", "bb", "cc", "dd");
  //方式1:
  list.stream().map(str -> str.toUpperCase()).forEach(System.out::println);
  //方式2:
  list.stream().map(String :: toUpperCase).forEach(System.out::println);

  //练习:获取员工姓名长度大于3的员工。
  List<Employee> employees = EmployeeData.getEmployees();
  employees.stream().filter(emp -> emp.getName().length() > 3).forEach(System.out::println);

  //练习:获取员工姓名长度大于3的员工的姓名。
  //方式1:
  employees.stream().filter(emp -> emp.getName().length() > 3)
    .map(emp -> emp.getName()).forEach(System.out::println);
  //方式2:
  employees.stream().map(emp -> emp.getName())
    .filter(name -> name.length() > 3).forEach(System.out::println);
  //方式3: 
  employees.stream().map(Employee::getName)
    // <R> Stream<R> map(Function<? super T, ? extends R> mapper);
    .filter(name -> name.length() > 3).forEach(System.out::println);
}

排序

//3-排序
@Test
public void test3() {
    //sorted()——自然排序,所谓自然排序是排序对象需要实现Comparable接口,重写compareTo方法
    // Integer 和 String 默认都是升序
    /**
     * 所谓升序:(compareTo(obj)的规则)
     *  - 如果当前对象 this 大于形参对象 obj,则返回正整数,
     *  - 如果当前对象 this 小于形参对象 obj,则返回负整数,
     *  - 如果当前对象 this 等于形参对象 obj,则返回零
     * 如果需要降序,可以把关键代码改为 return -(A-B)
     */
    Integer[] arr = new Integer[]{345,3,64,3,46,7,3,34,65,68};
    String[] arr1 = new String[]{"GG","DD","MM","SS","JJ"};

    Arrays.stream(arr).sorted().forEach(System.out::println);
    System.out.println(Arrays.toString(arr));//arr数组并没有因为升序,做调整。

    Arrays.stream(arr1).sorted().forEach(System.out::println);

    //因为Employee没有实现Comparable接口,所以报错!
//        List<Employee> list = EmployeeData.getEmployees();
//        list.stream().sorted().forEach(System.out::println);


    //sorted(Comparator com)——定制排序
    // 所谓定制排序就是实现 Comparator接口,重写compare()方法
    List<Employee> list = EmployeeData.getEmployees();
    // Stream<T> sorted(Comparator<? super T> comparator);
    // e1.getAge() - e2.getAge() 按照年龄升序
    list.stream().sorted((e1,e2) -> e1.getAge() - e2.getAge()).forEach(System.out::println);
    System.out.println("-----------------------");
    //针对于字符串从大到小排列
    // Stream<T> sorted(Comparator<? super T> comparator);
    Arrays.stream(arr1).sorted((s1,s2) -> -s1.compareTo(s2)).forEach(System.out::println);
//        Arrays.stream(arr1).sorted(String :: compareTo).forEach(System.out::println);
}

终止操作

匹配与查找

//1-匹配与查找
@Test
public void test1(){
// allMatch(Predicate p)——检查是否匹配所有元素。返回 boolean
//  练习:是否所有的员工的年龄都大于18
    List<Employee> list = EmployeeData.getEmployees();
    System.out.println(list.stream().allMatch(emp -> emp.getAge() > 18));
//  anyMatch(Predicate p)——检查是否至少匹配一个元素。返回 boolean
    //练习:是否存在年龄大于18岁的员工
    System.out.println(list.stream().anyMatch(emp -> emp.getAge() > 18));
//    练习:是否存在员工的工资大于 10000
    System.out.println(list.stream().anyMatch(emp -> emp.getSalary() > 10000));
//   findFirst——返回第一个元素 
    System.out.println(list.stream().findFirst().get());
}

@Test
public void test2(){
    // count——返回流中元素的总个数
    List<Employee> list = EmployeeData.getEmployees();
    System.out.println(list.stream().filter(emp -> emp.getSalary() > 7000).count());

//        max(Comparator c)——返回流中最大值
    //练习:返回最高工资的员工
    System.out.println(list.stream().max((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));

//        练习:返回最高的工资:
    //方式1:
    System.out.println(list.stream().max((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())).get().getSalary());
    //方式2:
    System.out.println(list.stream().map(emp -> emp.getSalary())
                       .max((salary1, salary2) -> Double.compare(salary1, salary2)).get());
    System.out.println(list.stream().map(emp -> emp.getSalary())
                       .max(Double::compare).get());

//        min(Comparator c)——返回流中最小值
//        练习:返回最低工资的员工
    System.out.println(list.stream()
                       .min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));


//        forEach(Consumer c)——内部迭代
    list.stream().forEach(System.out::println);


    //针对于集合,jdk8中增加了一个遍历的方法
    list.forEach(System.out::println);
    //针对于List来说,遍历的方式:① 使用Iterator ② 增强for ③ 一般for ④ forEach()
}

归约

//2-归约
@Test
public void test3(){
    //reduce(T identity, BinaryOperator)——可以将流中元素反复结合起来,得到一个值。返回 T
    //public interface BinaryOperator<T> extends BiFunction<T,T,T>
    /** 输入 T 和 U;返回 R
     * public interface BiFunction<T, U, R> {
     *  R apply (T t, U u);
     * }*/
    //练习1:计算1-10的自然数的和
    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    // 累加
    System.out.println(list.stream().reduce(0, (x1, x2) -> x1 + x2));
    System.out.println(list.stream().reduce(0, (x1, x2) -> Integer.sum(x1,x2)));
    System.out.println(list.stream().reduce(0, Integer::sum)); // 55
    // identity 起到初始值的作用
    System.out.println(list.stream().reduce(10, (x1, x2) -> x1 + x2)); // 65

    //  reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。返回 Optional<T>
    //  练习2:计算公司所有员工工资的总和
    List<Employee> employeeList = EmployeeData.getEmployees();
    System.out.println(employeeList.stream()
            .map(emp -> emp.getSalary())
            .reduce((salary1, salary2) -> Double.sum(salary1, salary2)));
    System.out.println(employeeList.stream()
            .map(Employee::getSalary)
            .reduce(Double::sum));
}

收集

//3-收集
@Test
public void test4(){
  List<Employee> list = EmployeeData.getEmployees();
  //  collect(Collector c)——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法
  //  练习1:查找工资大于6000的员工,结果返回为一个List或Set
  List<Employee> list1 = list.stream()
    .filter(emp -> emp.getSalary() > 6000)
    .collect(Collectors.toList());
  list1.forEach(System.out::println);
  System.out.println();
  list.forEach(System.out::println);

  System.out.println();
  //  练习2:按照员工的年龄进行排序,返回到一个新的List中
  List<Employee> list2 = list.stream().sorted((e1, e2) -> e1.getAge() - e2.getAge()).toList();
  list2.forEach(System.out::println);
//toList  Collector<T, ?, List<T>>把流中元素收集到List
// toSet Collector<T, ?, Set<T>>把流中元素收集到Set
// toCollection Collector<T, ?, C>把流中元素收集到创建的集合
}

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1909773034@qq.com

×

喜欢就点赞,疼爱就打赏