Java8的特性

简述

  • 速度更快
  • 代码更少(增加了新的语法 Lambda 表达式
  • 强大的 Stream API
  • 便于并行
  • 最大化减少空指针异常 Optional

一. lambda表达式

Lambda 表达式的基础语法:Java8中引入了一个新的操作符 “->” 该操作符称为箭头操作符或 Lambda 操作符 箭头操作符将 Lambda 表达式拆分成两部分:
左侧:Lambda 表达式的参数列表
右侧:Lambda 表达式中所需执行的功能, 即 Lambda 体
1.语法格式一:无参数,无返回值

() -> System.out.println("Hello Lambda!");

2.语法格式二:有一个参数,并且无返回值

(x) -> System.out.println(x)

3.语法格式三:若只有一个参数,小括号可以省略不写

x -> System.out.println(x)

4.语法格式四:有两个以上的参数,有返回值,并且 Lambda 体中有多条语句

Comparator<Integer> com = (x, y) -> {
    System.out.println("函数式接口");
    return Integer.compare(x, y);
};

5.语法格式五:若 Lambda 体中只有一条语句, return 和 大括号都可以省略不写

Comparator<Integer> com = (x, y) -> Integer.compare(x, y);

6.语法格式六:Lambda 表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型,即“类型推断”

(Integer x, Integer y) -> Integer.compare(x, y);

类型推断:上述 Lambda 表达式中的参数类型都是由编译器推断 得出的。Lambda 表达式中无需指定类型,程序依然可 以编译,这是因为 javac 根据程序的上下文,在后台 推断出了参数的类型。Lambda 表达式的类型依赖于上 下文环境,是由编译器推断出来的。这就是所谓的 “类型推断”

示例

1.调用Collections.sort()方法,通过定制排序比较两个Employee(先按年龄比,年龄相同的按照姓名比),使用Lambda表达式作为参数传递;

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

@Test
public void test1(){
    Collections.sort(emps, (e1, e2) -> {
        if(e1.getAge() == e2.getAge()){
            return e1.getName().compareTo(e2.getName());
        }else{
            return -Integer.compare(e1.getAge(), e2.getAge());
        }
    });
    for (Employee emp : emps) {
        System.out.println(emp);
    }
}

2.(1)声明函数式接口,接口中声明抽象方法,public String getValue(String str);
(2)声明类TestLambda,类中编写方法使用接口作为参数,将一个字符串转换成大写,并作为方法的返回值;
(3)再将一个字符串的第二个和第四个索引位置进行截取子串;

@FunctionalInterface
public interface MyFunction {
    public String getValue(String str);
}

//需求:用于处理字符串
public String strHandler(String str, MyFunction mf){//函数式接口MyFunction 
    return mf.getValue(str);
}
@Test
public void test2(){
    String trimStr = strHandler("\t\t\t 我是一个字符串   ", (str) -> str.trim());
    System.out.println(trimStr);

    String upper = strHandler("abcdef", (str) -> str.toUpperCase());
    System.out.println(upper);

    String newStr = strHandler("我是一个字符串,你也是一个字符串", (str) -> str.substring(2, 5));
    System.out.println(newStr);
}

3.(1)声明一个带两个泛型的函数式接口,泛型类型为

public interface MyFunction2<T, R> {
    public R getValue(T t1, T t2);
}

//需求:对于两个 Long 型数据进行处理
public void op(Long l1, Long l2, MyFunction2<Long, Long> mf){
    System.out.println(mf.getValue(l1, l2));
}

public void test3(){
    op(100L, 200L, (x, y) -> x + y);
    op(100L, 200L, (x, y) -> x * y);
}

二. 函数式接口

Lambda 表达式需要“函数式接口”的支持
函数式接口:只包含一个抽象方法的接口,称为函数式接口。
你可以通过 Lambda 表达式来创建该接口的对象。(若 Lambda 表达式抛出一个受检异常,那么该异常需要在目标接口的抽象方法上进行声明)。
我们可以在任意函数式接口上使用 @FunctionalInterface 注解,这样做可以检查它是否是一个函数式接口,同时 javadoc 也会包 含一条声明,说明这个接口是一个函数式接口。

函数式接口 参数类型 返回类型 用途
Consumer<T> 消费型接口 T void 对类型为T的对象应用操 作,包含方法: void accept(T t)
Supplier<T> 供给型接口 T 返回类型为T的对象,包 含方法:T get();
Function<T, R> 函数型接口 T R 对类型为T的对象应用操 作,并返回结果。结果 是R类型的对象。包含方 法:R apply(T t);
Predicate<T> 断定型接口 T boolean 确定类型为T的对象是否 满足某约束,并返回 boolean 值。包含方法 boolean test(T t);
BiFunction<T, U, R> T, U R 对类型为 T, U 参数应用 操作, 返回 R 类型的结 果。包含方法为R apply(T t, U u);
UnaryOperator<T>(Function子接口) T T 对类型为T 的对象进行一 元运算, 并返回T 类型的 结果。包含方法为T apply(T t);
BinaryOperator<T> (BiFunction 子接口) T, T T 对类型为T 的对象进行二 元运算, 并返回T类型的 结果。包含方法为T apply(T t1, T t2);
BiConsumer<T, U> T, U void 对类型为T, U 参数应用 操作。包含方法为void accept(T t, U u)
ToIntFunction<T> ToLongFunction<T> ToDoubleFunction<T> T int long double 分 别 计 算 int 、 long 、double、值的函数
IntFunction<R> LongFunction<R> DoubleFunction<R> int long double R 参数分别为int 、long 、double 类型的函数

Java8 内置的四大核心函数式接口

1.消费型接口

Consumer<T> --> void accept(T t);
//示例
//Consumer<T> 消费型接口 :
@Test
public void test1(){
    happy(10000, (m) -> System.out.println("年轻人喜欢消费,每次消费:" + m + "元"));
} 

public void happy(double money, Consumer<Double> con){
    con.accept(money);
}

2.供给型接口

Supplier<T> --> T get(); 

//示例
//Supplier<T> 供给型接口 :
@Test
public void test2(){
    List<Integer> numList = getNumList(10, () -> (int)(Math.random() * 100));

    for (Integer num : numList) {
        System.out.println(num);
    }
}

//需求:产生指定个数的整数,并放入集合中
public List<Integer> getNumList(int num, Supplier<Integer> sup){
    List<Integer> list = new ArrayList<>();

    for (int i = 0; i < num; i++) {
        Integer n = sup.get();
        list.add(n);
    }

    return list;
}

3.函数型接口

Function<T, R>  --> R apply(T t);

//示例
//Function<T, R> 函数型接口:
@Test
public void test3(){
    String newStr = strHandler("\t\t\t 我是一个字符串   ", (str) -> str.trim());
    System.out.println(newStr);

    String subStr = strHandler("我是一个字符串2", (str) -> str.substring(2, 5));
    System.out.println(subStr);
}

//需求:用于处理字符串
public String strHandler(String str, Function<String, String> fun){
    return fun.apply(str);
}

4.断言型接口

Predicate<T> --> boolean test(T t);

//示例
//Predicate<T> 断言型接口:
@Test
public void test4(){
    List<String> list = Arrays.asList("Hello", "sinosoft", "Lambda", "www", "ok");
    List<String> strList = filterStr(list, (s) -> s.length() > 3);

    for (String str : strList) {
        System.out.println(str);
    }
}

//需求:将满足条件的字符串,放入集合中
public List<String> filterStr(List<String> list, Predicate<String> pre){
    List<String> strList = new ArrayList<>();

    for (String str : list) {
        if(pre.test(str)){
            strList.add(str);
        }
    }
    return strList;
}

三. 方法引用与构造器引用

方法引用

当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!
(实现抽象方法的参数列表,必须与方法引用方法的参数列表保持一致!)
方法引用:使用操作符 “::” 将方法名和对象或类的名字分隔开来。
如下三种主要使用情况:

  • 对象::实例方法

  • 类::静态方法

  • 类::实例方法

注意:
①方法引用所引用的方法的参数列表与返回值类型,需要与函数式接口中抽象方法的参数列表和返回值类型保持一致!
②类::实例方法的这种引用方式必须满足 Lambda 的参数列表的第一个参数,是实例方法的调用者,第二个参数(或无参)是实例方法的参数时,格式: ClassName::MethodName
1.对象::实例方法

@Test
public void test1(){
    PrintStream ps = System.out;
    Consumer<String> con = (str) -> ps.println(str);
    con.accept("Hello World!");

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

    Consumer<String> con2 = ps::println;
    con2.accept("Hello Java8!");

    Consumer<String> con3 = System.out::println;
    con3.accept("Hello xiao ming");
}

@Test
public void test2(){
    Employee emp = new Employee(101, "张三", 18, 9999.99);

    Supplier<String> sup = () -> emp.getName();
    System.out.println(sup.get());

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

    Supplier<String> sup2 = emp::getName;
    System.out.println(sup2.get());
}

2.类::静态方法

@Test
public void test3(){
    BiFunction<Double, Double, Double> fun = (x, y) -> Math.max(x, y);
    System.out.println(fun.apply(1.5, 22.2));

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

    BiFunction<Double, Double, Double> fun2 = Math::max;
    System.out.println(fun2.apply(1.2, 1.5));
}

@Test
public void test4(){
    Comparator<Integer> com = (x, y) -> Integer.compare(x, y);

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

    Comparator<Integer> com2 = Integer::compare;
}

3.类::实例方法

@Test
public void test5(){
    BiPredicate<String, String> bp = (x, y) -> x.equals(y);
    System.out.println(bp.test("abcde", "abcde"));//true
    BiPredicate<String, String> bp2 = String::equals;
    System.out.println(bp2.test("abc", "abc"));//true
    System.out.println("-----------------------------------------");
    Function<Employee, String> fun = (e) -> e.show();
    System.out.println(fun.apply(new Employee()));//测试方法引用!
    System.out.println("-----------------------------------------");
    Function<Employee, String> fun2 = Employee::show;
    System.out.println(fun2.apply(new Employee()));//测试方法引用!
}

构造器引用

格式: ClassName::new
与函数式接口相结合,自动与函数式接口中方法兼容。
可以把构造器引用赋值给定义的方法,与构造器参数 列表要与接口中抽象方法的参数列表一致!

@Test
public void test6(){
    Supplier<Employee> sup = () -> new Employee();
    System.out.println(sup.get());

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

    Supplier<Employee> sup2 = Employee::new;
    System.out.println(sup2.get());
}

@Test
public void test7(){
    Function<String, Employee> fun = Employee::new;

    BiFunction<String, Integer, Employee> fun2 = Employee::new;
}

数组引用

@Test
public void test8(){
    Function<Integer, String[]> fun = (args) -> new String[args];
    String[] strs = fun.apply(10);
    System.out.println(strs.length);

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

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

四. Stream API

Java8中有两大最为重要的改变。第一个是 Lambda 表达式;另外一 个则是 Stream API(java.util.stream.*)。
Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。 使用Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询。也可以使用 Stream API 来并行执行操作。简而言之, Stream API 提供了一种高效且易于使用的处理数据的方式。

Stream 的操作三个步骤

  • 创建 Stream
    一个数据源(如:集合、数组),获取一个流
  • 中间操作
    一个中间操作链,对数据源的数据进行处理
  • 终止操作(终端操作)
    一个终止操作,执行中间操作链,并产生结果
    这里写图片描述

1.创建 Stream

@Test
public void test1(){
    //1. Collection 提供了两个方法  stream()顺序流 与 parallelStream()并行流
    List<String> list = new ArrayList<>();
    Stream<String> stream = list.stream(); //获取一个顺序流
    Stream<String> parallelStream = list.parallelStream(); //获取一个并行流

    //2. 通过 Arrays 中的 stream() 获取一个数组流
    Integer[] nums = new Integer[10];
    Stream<Integer> stream1 = Arrays.stream(nums);

    //3. 通过 Stream 类中静态方法 of()
    Stream<Integer> stream2 = Stream.of(1,2,3,4,5,6);

    //4. 创建无限流
    //迭代
    //iterate(final T seed, final UnaryOperator<T> f) seed 种子,也就是初始值;f 一元运算
    Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 2).limit(10);
    stream3.forEach(System.out::println);
    //生成
    Stream<Double> stream4 = Stream.generate(Math::random).limit(2);
    stream4.forEach(System.out::println);
}

2.中间操作

1)筛选与切片
filter——接收 Lambda , 从流中排除某些元素。
limit——截断流,使其元素不超过给定数量。
skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
distinct——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
先写一个集合

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)
);

filter

//内部迭代:迭代操作 Stream API 内部完成
@Test
public void test2(){
    //所有的中间操作不会做任何的处理
    Stream<Employee> stream = emps.stream()
        .filter((e) -> {
            System.out.println("测试中间操作");
            return e.getAge() <= 35;
        });

    //只有当做终止操作时,所有的中间操作会一次性的全部执行,称为“惰性求值”
    stream.forEach(System.out::println);
}

//外部迭代
@Test
public void test3(){
    Iterator<Employee> it = emps.iterator();

    while(it.hasNext()){
        System.out.println(it.next());
    }
}

limit

@Test
public void test4(){
    emps.stream()
        .filter((e) -> {
            System.out.println("短路!"); // &&  ||
            return e.getSalary() >= 5000;
        }).limit(3)
        .forEach(System.out::println);
}

skip

@Test
public void test5(){
    emps.parallelStream()
        .filter((e) -> e.getSalary() >= 5000)
        .skip(2)
        .forEach(System.out::println);
}

distinct

@Test
public void test6(){
    emps.stream()
        .distinct()
        .forEach(System.out::println);
}

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

方法 描述
map(Function f) 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
mapToDouble(ToDoubleFunction f) 接收一个函数作为参数,该函数会被应用到每个元 素上,产生一个新的 DoubleStream。
mapToInt(ToIntFunction f) 接收一个函数作为参数,该函数会被应用到每个元 素上,产生一个新的 IntStream。
mapToLong(ToLongFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 LongStream。
flatMap(Function f) 接收一个函数作为参数,将流中的每个值都换成另 一个流,然后把所有流连接成一个流

map

@Test
public void test1(){
    Stream<String> str = emps.stream()
        .map((e) -> e.getName());

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

    List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");

    Stream<String> stream = strList.stream()
           .map(String::toUpperCase);

    stream.forEach(System.out::println);

    Stream<Stream<Character>> stream2 = strList.stream()
           .map(TestStreamAPI1::filterCharacter);

    stream2.forEach((sm) -> {
        sm.forEach(System.out::println);
    });

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

    Stream<Character> stream3 = strList.stream()
           .flatMap(TestStreamAPI1::filterCharacter);

    stream3.forEach(System.out::println);
}

public static Stream<Character> filterCharacter(String str){
    List<Character> list = new ArrayList<>();

    for (Character ch : str.toCharArray()) {
        list.add(ch);
    }

    return list.stream();
}

3)排序
sorted()——自然排序 Comparable
sorted(Comparator com)——定制排序 Comparator

@Test
public void test2(){
    emps.stream()
        .map(Employee::getName)
        .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);
}

3.终止操作

更新下实体类Employee

public class Employee {

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

    public Employee() {
    }

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

    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 Employee(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;
        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 + ", status=" + status
                + "]";
    }



}
public enum Status {
    FREE, BUSY, VOCATION;
}

查找与匹配

allMatch——检查是否匹配所有元素
anyMatch——检查是否至少匹配一个元素
noneMatch——检查是否没有匹配的元素
findFirst——返回第一个元素
findAny——返回当前流中的任意元素
count——返回流中元素的总个数
max——返回流中最大值
min——返回流中最小值

方法 描述
allMatch(Predicate p) 检查是否匹配所有元素
anyMatch(Predicate p) 检查是否至少匹配一个元素
noneMatch(Predicate p) 检查是否没有匹配所有元素
findFirst() 返回第一个元素
findAny() 返回当前流中的任意元素
count() 返回流中元素总数
max(Comparator c) 返回流中最大值
min(Comparator c) 返回流中最小值
forEach(Consumer c) 内部迭代(使用 Collection 接口需要用户去做迭代,称为外部迭代。相反,Stream API 使用内部 迭代——它帮你把迭代做了)
@Test
public void test1(){
    boolean bl = emps.stream()
        .allMatch((e) -> e.getStatus().equals(Status.BUSY));                
    System.out.println(bl);

    boolean bl1 = emps.stream()
        .anyMatch((e) -> e.getStatus().equals(Status.BUSY));

    System.out.println(bl1);

    boolean bl2 = emps.stream()
        .noneMatch((e) -> e.getStatus().equals(Status.BUSY));

    System.out.println(bl2);
}

@Test
public void test2(){
    Optional<Employee> op = emps.stream()
        .sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))
        .findFirst();

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

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

    Optional<Employee> op2 = emps.parallelStream()
        .filter((e) -> e.getStatus().equals(Status.FREE))
        .findAny();

    System.out.println(op2.get());
}

@Test
public void test3(){
    long count = emps.stream()
                     .filter((e) -> e.getStatus().equals(Status.FREE))
                     .count();

    System.out.println(count);

    Optional<Double> op = emps.stream()
        .map(Employee::getSalary)
        .max(Double::compare);

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

    Optional<Employee> op2 = emps.stream()
        .min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));

    System.out.println(op2.get());
}

//注意:流进行了终止操作后,不能再次使用
@Test
public void test4(){
    Stream<Employee> stream = emps.stream()
     .filter((e) -> e.getStatus().equals(Status.FREE));

    long count = stream.count();

    stream.map(Employee::getSalary)
        .max(Double::compare);
}

归约

reduce(T identity, BinaryOperator) / reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。

方法 描述
reduce(T iden, BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。
reduce(BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。 返回 Optional<T>
List<Employee> emps = Arrays.asList(
        new Employee(102, "李四", 79, 6666.66, Status.BUSY),
        new Employee(101, "张三", 18, 9999.99, Status.FREE),
        new Employee(103, "王五", 28, 3333.33, Status.VOCATION),
        new Employee(104, "赵六", 8, 7777.77, Status.BUSY),
        new Employee(104, "赵六", 8, 7777.77, Status.FREE),
        new Employee(104, "赵六", 8, 7777.77, Status.FREE),
        new Employee(105, "田七", 38, 5555.55, Status.BUSY)
);
@Test
public void test1(){
    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);

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

    Optional<Double> op = emps.stream()
        .map(Employee::getSalary)
        .reduce(Double::sum);

    System.out.println(op.get());
}

//需求:搜索名字中 “六” 出现的次数
@Test
public void test2(){
    Optional<Integer> sum = emps.stream()
        .map(Employee::getName)
        .flatMap(TestStreamAPI1::filterCharacter)
        .map((ch) -> {
            if(ch.equals('六'))
                return 1;
            else 
                return 0;
        }).reduce(Integer::sum);

    System.out.println(sum.get());
}

收集

collect——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法

方法 描述
collect(Collector c) 将流转换为其他形式。接收一个 Collector接口的 实现,用于给Stream中元素做汇总的方法

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

方法 返回类型 作用 示例
toList List<T> 把流中元素收集到List List<Employee> emps= list.stream().collect(Collectors.toList());
toSet Set<T> 把流中元素收集到Set Set<Employee> emps= list.stream().collect(Collectors.toSet());
toCollection Collection<T> 把流中元素收集到创建的集合 Collection<Employee>emps=list.stream().collect(Collectors.toCollection(ArrayList::new));
counting Long 计算流中元素的个数 long count = list.stream().collect(Collectors.counting());
summingInt Integer 对流中元素的整数属性求和 inttotal=list.stream().collect(Collectors.summingInt(Employee::getSalary));
averagingInt Double 计算流中元素Integer属性的平均值 doubleavg= list.stream().collect(Collectors.averagingInt(Employee::getSalary));
summarizingInt IntSummaryStatistics 收集流中Integer属性的统计值。如:平均值 IntSummaryStatisticsiss= list.stream().collect(Collectors.summarizingInt(Employee::getSalary));
joining String 连接流中每个字符串 String str= list.stream().map(Employee::getName).collect(Collectors.joining());
maxBy Optional<T> 根据比较器选择最大值 Optional<Emp>max= list.stream().collect(Collectors.maxBy(comparingInt(Employee::getSalary)));
minBy Optional<T> 根据比较器选择最小值 Optional<Emp> min = list.stream().collect(Collectors.minBy(comparingInt(Employee::getSalary)));
reducing 归约产生的类型 从一个作为累加器的初始值 开始,利用BinaryOperator与流中元素逐个结合,从而归 约成单个值 inttotal=list.stream().collect(Collectors.reducing(0, Employee::getSalar, Integer::sum));
collectingAndThen 转换函数返回的类型 包裹另一个收集器,对其结 果转换函数 inthow= list.stream().collect(Collectors.collectingAndThen(Collectors.toList(), List::size));
groupingBy Map<K, List<T>> 根据某属性值对流分组,属 性为K,结果为V Map<Emp.Status, List<Emp>> map= list.stream().collect(Collectors.groupingBy(Employee::getStatus));
partitioningBy Map<Boolean, List<T>> 根据true或false进行分区 Map<Boolean,List<Emp>>vd= list.stream().collect(Collectors.partitioningBy(Employee::getManage));
@Test
public void test3(){
    List<String> list = emps.stream()
        .map(Employee::getName)
        .collect(Collectors.toList());

    list.forEach(System.out::println);

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

    Set<String> set = emps.stream()
        .map(Employee::getName)
        .collect(Collectors.toSet());

    set.forEach(System.out::println);

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

    HashSet<String> hs = emps.stream()
        .map(Employee::getName)
        .collect(Collectors.toCollection(HashSet::new));

    hs.forEach(System.out::println);
}

@Test
public void test4(){
    Optional<Double> max = emps.stream()
        .map(Employee::getSalary)
        .collect(Collectors.maxBy(Double::compare));

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

    Optional<Employee> op = emps.stream()
        .collect(Collectors.minBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));

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

    Double sum = emps.stream()
        .collect(Collectors.summingDouble(Employee::getSalary));

    System.out.println(sum);

    Double avg = emps.stream()
        .collect(Collectors.averagingDouble(Employee::getSalary));

    System.out.println(avg);

    Long count = emps.stream()
        .collect(Collectors.counting());

    System.out.println(count);

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

    DoubleSummaryStatistics dss = emps.stream()
        .collect(Collectors.summarizingDouble(Employee::getSalary));

    System.out.println(dss.getMax());
}

//分组
@Test
public void test5(){
    Map<Status, List<Employee>> map = emps.stream()
        .collect(Collectors.groupingBy(Employee::getStatus));

    System.out.println(map);
}

//多级分组
@Test
public void test6(){
    Map<Status, Map<String, List<Employee>>> map = emps.stream()
        .collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
            if(e.getAge() >= 60)
                return "老年";
            else if(e.getAge() >= 35)
                return "中年";
            else
                return "成年";
        })));

    System.out.println(map);
}

//分区
@Test
public void test7(){
    Map<Boolean, List<Employee>> map = emps.stream()
        .collect(Collectors.partitioningBy((e) -> e.getSalary() >= 5000));

    System.out.println(map);
}

//
@Test
public void test8(){
    String str = emps.stream()
        .map(Employee::getName)
        .collect(Collectors.joining("," , "----", "----"));

    System.out.println(str);
}

@Test
public void test9(){
    Optional<Double> sum = emps.stream()
        .map(Employee::getSalary)
        .collect(Collectors.reducing(Double::sum));

    System.out.println(sum.get());
}

并行流与串行流

并行流就是把一个内容分成多个数据块,并用不同的线程分别处理每个数据块的流。

Java 8 中将并行进行了优化,我们可以很容易的对数据进行并行操作。Stream API 可以声明性地通过 parallel() 与 sequential() 在并行流与顺序流之间进行切换。

了解 Fork/Join 框架

Fork/Join 框架:就是在必要的情况下,将一个大任务,进行拆分(fork)成若干个 小任务(拆到不可再拆时),再将一个个的小任务运算的结果进行 join 汇总.

Fork/Join 框架与传统线程池的区别

采用 “工作窃取”模式(work-stealing):
当执行新的任务时它可以将其拆分分成更小的任务执行,并将小任务加到线 程队列中,然后再从一个随机线程的队列中偷一个并把它放在自己的队列中。

相对于一般的线程池实现,fork/join框架的优势体现在对其中包含的任务的 处理方式上.在一般的线程池中,如果一个线程正在执行的任务由于某些原因 无法继续运行,那么该线程会处于等待状态.而在fork/join框架实现中,如果 某个子问题由于等待另外一个子问题的完成而无法继续运行.那么处理该子 问题的线程会主动寻找其他尚未运行的子问题来执行.这种方式减少了线程 的等待时间,提高了性能.

public class ForkJoinCalculate extends RecursiveTask<Long>{

    /**
     * 
     */
    private static final long serialVersionUID = 13475679780L;

    private long start;
    private long end;

    private static final long THRESHOLD = 10000L; //临界值

    public ForkJoinCalculate(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        long length = end - start;

        if(length <= THRESHOLD){
            long sum = 0;

            for (long i = start; i <= end; i++) {
                sum += i;
            }

            return sum;
        }else{
            long middle = (start + end) / 2;

            ForkJoinCalculate left = new ForkJoinCalculate(start, middle);
            left.fork(); //拆分,并将该子任务压入线程队列

            ForkJoinCalculate right = new ForkJoinCalculate(middle+1, end);
            right.fork();

            return left.join() + right.join();
        }

    }

}
public class TestForkJoin {

    @Test
    public void test1(){
        long start = System.currentTimeMillis();

        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinCalculate(0L, 10000000000L);

        long sum = pool.invoke(task);
        System.out.println(sum);

        long end = System.currentTimeMillis();

        System.out.println("耗费的时间为: " + (end - start)); //
    }

    @Test
    public void test2(){
        long start = System.currentTimeMillis();

        long sum = 0L;

        for (long i = 0L; i <= 10000000000L; i++) {
            sum += i;
        }

        System.out.println(sum);

        long end = System.currentTimeMillis();

        System.out.println("耗费的时间为: " + (end - start)); //
    }

    @Test
    public void test3(){
        long start = System.currentTimeMillis();

        Long sum = LongStream.rangeClosed(0L, 10000000000L)
                             .parallel()
                             .sum();
        System.out.println(sum);

        long end = System.currentTimeMillis();

        System.out.println("耗费的时间为: " + (end - start)); //
    }

}

五. 接口中的默认方法与静态方法

Java 8中允许接口中包含具有具体实现的方法,该方法称为 “默认方法”,默认方法使用 default 关键字修饰。

接口默认方法的”类优先”原则 :

若一个接口中定义了一个默认方法,而另外一个父类或接口中 又定义了一个同名的方法时

  • 选择父类中的方法。如果一个父类提供了具体的实现,那么接口中具有相同名称和参数的默认方法会被忽略。
  • 接口冲突。如果一个父接口提供一个默认方法,而另一个接 口也提供了一个具有相同名称和参数列表的方法(不管方法 是否是默认方法),那么必须覆盖该方法来解决冲突

接口中允许添加静态方法

public interface MyFun {

    default String getName(){
        return "Hello Java!!!";
    }
}

public interface MyInterface {

    default String getName(){
        return "Hello World";
    }

    public static void show(){
        System.out.println("接口中的静态方法");
    }
}

public class MyClass {

    public String getName(){
        return "Hello kkk";
    }

}

public class SubClass extends MyClass implements MyFun, MyInterface{

    @Override
    public String getName() {
        return MyInterface.super.getName();
    }

}

六. 时间日期API

LocalDate、LocalTime、LocalDateTime

LocalDate、LocalTime、LocalDateTime 类的实 例是不可变的对象,分别表示使用 ISO-8601日 历系统的日期、时间、日期和时间。它们提供 了简单的日期或时间,并不包含当前的时间信 息。也不包含与时区相关的信息。

方法 描述 示例
now() 静态方法,根据当前时间创建对象 LocalDate localDate = LocalDate.now();LocalTime localTime = LocalTime.now(); LocalDateTime localDateTime = LocalDateTime.now();
of() 静态方法,根据指定日期/时间创建对象 LocalDate localDate = LocalDate.of(2016, 10, 26);LocalTime localTime = LocalTime.of(02, 22, 56); LocalDateTime localDateTime = LocalDateTime.of(2016, 10, 26, 12, 10, 55);
plusDays, plusWeeks,plusMonths, plusYears 向当前 LocalDate 对象添加几天、几周、几个月、几年
minusDays, minusWeeks,minusMonths, minusYears 从当前 LocalDate 对象减去几天、几周、几个月、几年
plus, minus 添加或减少一个 Duration 或 Period
withDayOfMonth, withDayOfYear, withMonth, withYear 将月份天数、年份天数、月份、年份 修 改 为 指 定 的 值 并 返 回 新 的LocalDate 对象
getDayOfMonth 获得月份天数(1-31)
getDayOfYear 获得年份天数(1-366)
getDayOfWeek 获得星期几(返回一个 DayOfWeek枚举值)
getMonth 获得月份, 返回一个 Month 枚举值
getMonthValue 获得月份(1-12)
getYear 获得年份
until 获得两个日期之间的 Period 对象,或者指定 ChronoUnits 的数字
isBefore, isAfter 比较两个 LocalDate
isLeapYear 判断是否是闰年

Instant 时间戳

用于“时间戳”的运算。它是以Unix元年(传统 的设定为UTC时区1970年1月1日午夜时分)开始 所经历的描述进行运算

Duration 和 Period

  • Duration:用于计算两个“时间”间隔
  • Period:用于计算两个“日期”间隔

日期的操纵

七. 其他新特性

Optional 类

Optional 类(java.util.Optional) 是一个容器类,代表一个值存在或不存在,

原来用 null 表示一个值不存在,现在 Optional 可以更好的表达这个概念。并且可以避免空指针异常。 常用方法:
Optional.of(T t) : 创建一个 Optional 实例
Optional.empty() : 创建一个空的 Optional 实例
Optional.ofNullable(T t):若 t 不为 null,创建 Optional 实例,否则创建空实例
isPresent() : 判断是否包含值
orElse(T t) : 如果调用对象包含值,返回该值,否则返回t
orElseGet(Supplier s) :如果调用对象包含值,返回该值,否则返回 s 获取的值
map(Function f): 如果有值对其处理,并返回处理后的Optional,否则返回 Optional.empty()
flatMap(Function mapper):与 map 类似,要求返回值必须是Optional

@Test
public void test1(){
    Optional<Employee> op = Optional.of(new Employee());
    Employee emp = op.get();
    System.out.println(emp);
}

@Test
public void test2(){
    Optional<Employee> op = Optional.ofNullable(null);
    System.out.println(op.get());

    Optional<Employee> op1 = Optional.empty();
    System.out.println(op1.get());
}

@Test
public void test3(){
    Optional<Employee> op = Optional.ofNullable(new Employee());

    if(op.isPresent()){
        System.out.println(op.get());
    }

    Employee emp = op.orElse(new Employee("张三"));
    System.out.println(emp);

    Employee emp2 = op.orElseGet(() -> new Employee());
    System.out.println(emp2);
}

@Test
public void test4(){
    Optional<Employee> op = Optional.of(new Employee(101, "张三", 18, 9999.99));

    Optional<String> op2 = op.map(Employee::getName);
    System.out.println(op2.get());

    Optional<String> op3 = op.flatMap((e) -> Optional.of(e.getName()));
    System.out.println(op3.get());
}

猜你喜欢

转载自blog.csdn.net/wush93/article/details/80287982