【JavaSE】java8 新特性


前言:

java8的好处: 速度更快、代码更少(Lambda表达式)、强大的Stream API、便于并行、最大化减少空指针异常(Optoinal)、Nashorn引擎,允许在JVM上运行JS应用等

 

1.Lambda表达式*

Lambda是一个匿名函数,我们可以把Lambda表达式理解为是 一段可以传递的代码(将代码像数据一样进行传递)。使用它可以写出更简洁、更灵活的代码。作为一种更紧凑的代码风格,使Java的语言表达能力得到了提升。

public class test_Lambda{

    // 1.举例: (o1,o2) -> Integer.compare(o1,o2);
    // 2.格式:
    //      -> :Lambda操作符,或 箭头操作符
    //          左边:Lambda形参列表(其实是接口中的抽象方法的形参列表)
    //          右边:Lambda体(其实是重写抽象方法的方法体)
    // 3.使用: 分为6种情况(格式)介绍
    //      * 左边:Lambda形参列表的参数类型可以省略; Lambda若只有一个参数,可以省略小括号
    //      * 右边:Lambda体应使用一对大括号包裹;Lambda体若只有一条执行语句(包含return语句),可以省略该大括号和return关键字(省略大括号则必须省略return);
    // 4.本质: 作为函数式接口的实例(实现类对象)[只有一个抽象方法的接口,也称为函数式接口]

    /* 1.无参无返回值 */
    public static void t1(){
        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                System.out.println("我爱北京天安门~");
            }
        };
        r1.run();

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

        Runnable r2 = () -> {
            System.out.println("我爱地球!");
        };
        r2.run();
    }

    /* 2.有参数无返回值 */
    public static void t2(){
        Consumer<String> con = new Consumer<String>() {
            @Override
            public void accept(String s) {
                System.out.println(s);
            }
        };
        con.accept("abc");

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

        Consumer<String> con1 = (String s) -> {
            System.out.println(s);
        };
        con1.accept("def");
    }

    /* 3.数据类型可以省略,因为可由编译器推断得出,称为 “类型推断” */
    public static void t3(){
        Consumer<String> con1 = (String s) -> {
            System.out.println(s);
        };
        con1.accept("def");

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

        Consumer<String> con2 = (s) -> {
            System.out.println(s);
        };
        con1.accept("def2");
    }

    /* 4.Lambda若需要一个参数,参数的小括号可以省略 */
    public static void t4(){
        Consumer<String> con1 = (s) -> {
            System.out.println(s);
        };
        con1.accept("def1");

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

        Consumer<String> con2 = s -> {
            System.out.println(s);
        };
        con1.accept("def2");
    }

    /* 5.Lambda若需要两个或以上的参数,多条执行语句,并且可以有返回值 */
    public static void t5(){
        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, 21));
    }

    /* 6.若Lambda体只有一条语句时,return与大括号若有,都可以省略 */
    public static void t6(){
        Comparator<Integer> com1 = (o1,o2) -> {
            return o1.compareTo(o2);
        };
        System.out.println(com1.compare(12, 21));

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

        Comparator<Integer> com2 = (o1,o2) -> o1.compareTo(o2);
        System.out.println(com2.compare(12, 21));
    }


    public static void main(String[] args) {
        t6();
    }
}

 

2.函数式(Functoinal)接口

如果一个接口中,只声明了一个抽象式方法,则此接口就称为函数式接口
 
你可以通过Lambda表达式来创建该接的对象。(若Lambda表达式抛出一个受检异常(即:非运行时异常),那么该异常需要在目标接口的抽象方法上进行声明)
 
我们可以在一个接口上使用 @Functionallnterface注解,这样做可以检查它是否是一个函数式接口。同时javadoc也会包含一条声明,说明这个接口是一个函数式接口。
 
在java.util.function包下定义了Java8的丰富的函数式接口

在这里插入图片描述

public class test {

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

    public static List<String> t2(List<String> list, Predicate<String> pre){
        // 根据给定的pre规则来过滤字符串
        ArrayList<String> list1 = new ArrayList<>();
        for (String s : list) {
            if(pre.test(s)){
                list1.add(s);
            }
        }
        return list1;
    }

    public static void main(String[] args) {
        /* 1.Consumer */
        t1(100, new Consumer<Double>() {
            @Override
            public void accept(Double aDouble) {
                System.out.println("消费了"+ aDouble + "r");
            }
        });

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

        t1(100,aDouble -> System.out.println("消费了"+ aDouble + "r"));

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

        /* 2.Predicate */
        List<String> list = new ArrayList<>();
        list.add("ad");
        list.add("abc");
        list.add("fwf");
        list.add("w");

        List<String> strings = t2(list, new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return s.length() >= 2;
            }
        });
        System.out.println(strings);

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

        List<String> strings1 = t2(list, s -> s.length() >= 2);
        System.out.println(strings1);
        
    }

}


 

3.方法引用和构造器引用

● 当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!
 
● 方法引用可以看做是Lambda表达式深层次的表达。换句话说,方法引用就是Lambda表达式,也就是函数式接口的一个实例,通过方法的名字来指向一个方法,可以认为是Lambda表达式的一个语法糖。
 
● 要求:实现接口的抽象方法的参数列表和返回值类型,必须与方法引用的
方法的参数列表和返回值类型保持一致!
 
● 格式:使用操作符“:”将类(或对象)与方法名分隔开来。
 
● 如下三种主要使用情况:
   对象:实例方法名
   类:静态方法名
   类:实例方法名

 

3.1 对象 :: 非静态方法

public class test {

    /*
        方法引用的使用
        1.使用情境: Lambda体的操作已经有实现的方法,可以使用方法引用
        2.方法引用: 本质上就是Lambda表达式,而Lambda表达式作为函数式接口的实例,所以方法引用,也是函数式接口的实例
        3.使用格式: 类(或对象) :: 方法名
        4.具体分为如下三种情况:
            对象 :: 非静态方法
            类   :: 静态方法
            类   :: 非静态方法
        5.方法引用的要求: 要求接口中的抽象方法形参列表和返回值类型与方法引用中的形参列表和返回值类型相同
     */

	/* 情况1:对象 :: 非静态方法 */
    // Consumer中的 void accept(T t)
    // PrintStream中的 void println(T t)
    public static void t1(){
        Consumer<String> con1 = str -> System.out.println(str);
        con1.accept("abc");

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

        PrintStream ps = System.out;
        Consumer<String> con2 = ps::println;
        con2.accept("123");
    }

    // Supplier中的 T get()
    // person中的 String getName()
    public static void t2(){
        person p = new person(12,"张三");
        Supplier<String> sup1 = () -> p.getName();
        System.out.println(sup1.get());

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

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

    public static void main(String[] args) {
        t2();
    }
}

 

3.2 类 :: 静态方法

public class test {

    /* 情况2: 类 :: 静态方法 */
    // Comparator中的 int compare(T t1,T t2)
    // Integer中的 int compare(T t1,T t2)
    public static void t1(){
        Comparator<Integer> com1 = (t1, t2) -> Integer.compare(t1,t2);
        System.out.println(com1.compare(12, 13));

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

        Comparator<Integer> com2 = Integer::compare;
        System.out.println(com2.compare(13, 12));
        // Function中的 R apply(T t)
        // Math中的 Long Math(Double d)
    }

    /* 情况3 类 :: 非静态方法 */
    // Comparator中的 int compara(T t1,T t2)
    // String中的 int t1.compareTo(t2)
    public static void t2(){
        Comparator<String> com1 = (t1,t2) -> t1.compareTo(t2);
        System.out.println(com1.compare("abc", "ade"));

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

        Comparator<String> com2 = String::compareTo;
        System.out.println(com2.compare("ade", "abc"));
    }

    // Function中的 R apply(T t)
    // person中的 String getName()
    public static void t3(){
        person p = new person(12,"李四");
        Function<person,String> func1 = e -> e.getName();
        System.out.println(func1.apply(p));

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

        Function<person,String> func2 = person::getName;
        System.out.println(func2.apply(p));
    }

    public static void main(String[] args) {
        t3();
    }
}

 

3.3 构造器引用

public class test {

    /* 1.构造器引用: 和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致。抽象方法的返回值类型即为构造器所属的对 */
    // Supplier中的 T get()
    // person的 new person()
    public static void t1(){
        Supplier<person> sup1 = () -> new person();
        person person1 = sup1.get();
        System.out.println(person1);

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

        Supplier<person> sup2 = person::new;
        package1.person person2 = sup2.get();
        System.out.println(person2);

    }

    // Function中的 R apply(T t)
    // peron的 person(int age)
    public static void t2(){
        Function<Integer,person> func1 = age -> new person(age);
        person apply1 = func1.apply(12);
        System.out.println(apply1);

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

        Function<Integer,person> func2 = person::new;
        person apply2 = func2.apply(34);
        System.out.println(apply2);
    }

    // BiFunction中的 R Function(T t,U u)
    // person中的 new person(int age,Strign name)
    public static void t3(){
        BiFunction<Integer,String,person> bif1 = (age,name) -> new person(age,name);
        person p1 = bif1.apply(12, "张三");
        System.out.println(p1);

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

        BiFunction<Integer,String,person> bif2 = person::new;
        person p2 = bif2.apply(45, "李四");
        System.out.println(p2);
    }

    // 数组引用: 把数组看成一个特殊的类.和构造器引用一致
    // Function中的 R apply(T t)
    public static void t4(){
        Function<Integer,String[]> func1 = lenght -> new String[lenght];
        String[] apply1 = func1.apply(10);
        System.out.println(apply1.length);

        System.out.println("--------");
        Function<Integer,String[]> func2 = String[]::new;
        String[] apply2 = func2.apply(12);
        System.out.println(apply2.length);
    }

    public static void main(String[] args) {
        t4();
    }
}

 

4.Stream API*

● Java8中有两大最为重要的改变。第一个是 Lambda表达式; 另外一个则 是 Stream APl.
 
Stream API(java.util.stream)把真正的函数式编程风格引入到Java中。这是目前为止对Java类库最好的补充,因为Stream APl可以极大提供Java程序员的生产力,让程序员写出高效率、干净、简洁的代码。
 
● Stream是Java8中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API对集合数据进行操作,就类似于使用SQL执行的数据库查。也可以使用Stream API来并行执行操作。简言之,Stream API提供了一种高效且易于使用的处理数据的方式。

● 实际开发中,项目中多数数据源都来自于Mysql,Oracle等。但现在数据源可以更多了,有MongDB,Radis等,而这些NoSQL的数据就需要Java层面去处理。
 
● Stream和Collection集合的区别:Collection是一种静态的内存数据结构,而Stream是有关计算的。前者是主要面向内存,存储在内存中,后者主要是面向CPU,通过CPU实现计算。

 
注意
①Stream自己不会存储元素。
②Stream不会改变源对象。相反,他们会返回一个持有结果的新Stream。
③Stream操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。

● 1.创建Stream
一个数据源(如:集合、数组),获取一个流
 
● 2.中间操作
一个中间操作链,对数据源的数据进行处理
 
● 3.终止操作(终端操作)
一旦执行终止操作,就执行中间操作链,并产生结果。之后,不会再被使用

 

4.1 Stream的实例化

public class Employee implements Comparable<Employee>{
    private int id;
    private String name;
    private int age;
    private double salary;

	public Employee(){
        
    }

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

    public int getAge() {
        return age;
    }

    public double getSalary() {
        return salary;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", salary=" + 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;
        return name != null ? name.equals(employee.name) : employee.name == null;
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        return result;
    }

    @Override
    public int compareTo(Employee e) {
        return Double.compare(salary,e.getSalary());
    }
}

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,"马云",12,9876.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;
    }

}

 
创建方式1:通过集合

Java8中的Collection接口被扩展,提供了两个获取流的方法:
● default Stream stream(): 返回一个顺序流
● default Stream parallelStream(): 返回一个并行流

public class Main{
	public static void main(String[] args){
        List<Employee> employees = EmployeeData.getEmployees();

        // default Stream<E> stream(): 返回一个顺序流
        Stream<Employee> stream = employees.stream(); // 按顺序取数据

        // default Stream<E> parallelStream(): 返回一个并行流
        Stream<Employee> employeeStream = employees.parallelStream(); // 并行取数据,通过线程
    }
}

创建方式2:通过数组

Java8中的Arrays的静态方法stream)可以获取数组流:
● static Stream stream(T[] array): 返回一个流
 
重载形式,能够处理对应基本类型的数组:
● public static IntStream stream(int[]array)
● public static LongStream stream(long[]array)
● public static DoubleStream stream(double[]array)

public class Main{
	public static void main(String[] args){
        int[] arr = new int[]{1,2,3,4,5,6};
        // 调用Arrays.类static<T>Stream<T>stream(T[]array):返回一个流
        IntStream stream = Arrays.stream(arr);

        Employee e1 = new Employee(1,"a",12,12);
        Employee e2 = new Employee(2,"b",13,22);
        Employee[] employees = new Employee[]{e1,e2};

        Stream<Employee> stream1 = Arrays.stream(employees);
    }
}

创建方式3: 通过Stream的of()

可以调用Stream类静态方法of),通过显示值创建一个
流。它可以接收任意数量的参数。
● public static Stream of(T.values): 返回一个流

public class Main{
	public static void main(String[] args){
		
	}
}

 

4.2 Stream的中间操作

多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何的处理!而在终止操作时一次性全部处理,称为“惰性求值”

 

4.2.1 筛选与切片

filter(Predicate p): 接收Lambda,从流中排除某些元素
limit(long maxSize): 截断流,使其元素不超过给定数量
skip(long n): 跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回一个空流。与limit(n)互补

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

public class Main{
	public static void main(String[] args) {
        List<Employee> list = EmployeeData.getEmployees();

        // 1.filter(Predicate p)
        Stream<Employee> stream = list.stream();
        // 查询工资大于7000的员工
        stream.filter(e -> e.getSalary()>7000).forEach(System.out::println);

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

        // 2.limit(long maxSize)
        Stream<Employee> stream1 = list.stream();
        stream1.limit(3).forEach(System.out::println);

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

        // 3.skip(long n)
        Stream<Employee> stream2 = list.stream();
        stream2.skip(3).forEach(System.out::println);

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

        // 4.distinct()
        list.add(new Employee(1001,"马化腾",45,4000));
        for (Employee employee : list) {
            System.out.println(employee);
        }
        System.out.println("我是分割线~");
        Stream<Employee> stream3 = list.stream();
        stream3.distinct().forEach(System.out::println);
    }
}

 

4.2.2 映射

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

public class test{

    public static Stream<Character> fromStringToStream(String str){
        ArrayList<Character> list= new ArrayList<>();
        for(Character c:str.toCharArray()){
            list.add(c);
        }
        return list.stream();
    }

    public static void main(String[] args) {
        // 1.map(Function f)
        List<String> strings = Arrays.asList("aa", "bb", "cc", "dd");
        strings.stream().map(String::toUpperCase).forEach(System.out::println);

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

        // 获取名字大于3的员工姓名
        List<Employee> employees = EmployeeData.getEmployees();
        Stream<String> stringStream = employees.stream().map(Employee::getName);
        stringStream.filter(str -> str.length()>3).forEach(System.out::println);

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

        // 将流中的每个元素取出到一个流中
        Stream<Stream<Character>> streamStream = strings.stream().map(test::fromStringToStream);
        streamStream.forEach(s -> s.forEach(System.out::println));

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

        // 2.flatMap(Function f)
        Stream<Character> characterStream = strings.stream().flatMap(test::fromStringToStream);
        characterStream.forEach(System.out::println);

    }
}

 

4.3.3 排序

sorted(): 产生一个新流,其中按自然顺序排序
sorted(Comparator com): 产生一个新流,其中按比较器顺序排序

public class test{

    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(12, 45, 2, 12, 6, 90);

        // 1.自然排序
        list.stream().sorted().forEach(System.out::println);
        List<Employee> employees= EmployeeData.getEmployees();
        employees.stream().sorted().forEach(System.out::println);

        // 2.定制排序
        employees.stream().sorted((e1,e2) ->{
            int i = Integer.compare(e1.getAge(),e2.getAge());
            return i!=0?i:e1.getName().compareTo(e2.getName());
        }).forEach(System.out::println);
    }
}

 

4.3 Stream的终止操作

终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如:List、Integer或者是void。
流进行了终止操作后,不能再次使用。

 

4.3.1 匹配与查找

allMatch(Predicate p): 检查是否匹配所有元素
anyMatch(Predicate p): 检查是否至少匹配一个元素
noneMatch(Predicate p): 检查是否没有匹配所有元素
findFirst(): 返回第一个元素
findAny(): 返回当前流中的任意元素

count(): 返回流中元素总数
max(Comparator c): 返回流中最大值
min(Comparator c): 返回流中最小值
forEach(Consumer c): 内部迭代(使用Collection接口需要用户去做迭代,称为外部迭代。相反,Stream API使用内部迭代—它帮你把迭代做了)

public class test{

    public static void main(String[] args) {
        List<Employee> employees = EmployeeData.getEmployees();

        // 1.allMatch(Predicate p):
        // 是否所有员工的年龄都大于18
        System.out.println(employees.stream().allMatch(employee -> employee.getAge() > 18)); // false

        // 2.anyMatch(Predicate p):
        // 判断是否至少一个工资大于9000
        System.out.println(employees.stream().anyMatch(employee -> employee.getSalary() > 9000)); // true

        // 3.noneMatch(Predicate p)
        // 是否所有员工都不小于18
        System.out.println(employees.stream().noneMatch(employee -> employee.getSalary() < 2000)); // true

        // 4.findFirst()
        System.out.println(employees.stream().sorted().findFirst()); // Optional[Employee{id=1008, name='扎克伯格', age=35, salary=2500.32}]

        // 5.findAny()
        System.out.println(employees.stream().findAny()); // Optional[Employee{id=1001, name='马化腾', age=34, salary=6000.38}]

        // 6.count()
        System.out.println(employees.stream().filter(e -> e.getSalary()>5000).count()); // 5

        // 7.max(Comparator c)
        System.out.println(employees.stream().max(Employee::compareTo)); // Optional[Employee{id=1002, name='马云', age=12, salary=9876.12}]

        // 8.min(Comparator c)
        System.out.println(employees.stream().filter(e -> e.getName().length()>2).min(Employee::compareTo)); // Optional[Employee{id=1008, name='扎克伯格', age=35, salary=2500.32}]
        // 返回最低的工资
        Stream<Double> doubleStream = employees.stream().map(Employee::getSalary);
        System.out.println(doubleStream.min(Double::compareTo));

        // 9.forEach(Consumer c) -- 内部迭代
        employees.stream().filter(e -> e.getAge()>20).forEach(System.out::println); // ...
        employees.forEach(System.out::println);
    }
}

 

4.3.2 归约

reduce(T iden,BinaryOperator b): 可以将流中元素反复结合起来,得到一个值。返回T
educe(BinaryOperator b): 可以将流中元素反复结合起来,得到一个值。返回Optional<T>

public class test{

    public static void main(String[] args) {
        // 1.reduce(T iden,BinaryOperator b)
        // 计算1-10的和
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        System.out.println(list.stream().reduce(0, Integer::sum));
        // 计算所有员工工资和
        List<Employee> employees = EmployeeData.getEmployees();
        Stream<Double> doubleStream = employees.stream().map(Employee::getSalary);
        System.out.println(doubleStream.reduce(0.0, Double::sum));
    }
}

 

4.3.3 收集

collect(Collector c): 将流转换为其他形式。接收一个Collector接口的实现,用于给Stream中元素做汇总的方法
 
Collector接口中方法的实现决定了如何对流执行收集的操作(如收集到List、Set、Map).另外,Collectors实用类提供了很多静态方法,可以方便地创建常见收集器实例,具体方法与实例如下:

List<T> toList(): 把流中元素收集到List
Set<T> toSet(): 把流中元素收集到Set
Collection<T> toColletion(): 把流中元素收集到创建的集合

public class test{

    public static void main(String[] args) {
        List<Employee> employees = EmployeeData.getEmployees();
        // 查找工资大于6000的员工,将结果返回一个list或set
        List<Employee> collect = employees.stream().filter(e -> e.getSalary() > 7000).collect(Collectors.toList());
        collect.forEach(System.out::println);

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

        Set<Employee> collect1 = employees.stream().filter(e -> e.getSalary() > 7000).collect(Collectors.toSet());
        collect1.forEach(System.out::println);

    }
}

 

5.Optional类

● Optional<T>类Gava.util.Optional)是一个容器类,它可以保存类型T的值,代表这个值存在。或者仅仅保存nul,表示这个值不存在。原来用null表示一个值不存在,现在Optional可以更好的表达这个概念。并且可以避免空指针异常。
 
● Optional类的Javadoc描述如下:这是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象

● Optiona提供很多有用的方法,这样我们就不用显式进行空值检测。
 
● 创建。ptional类对象的方法:
Optional.of(T t): 创建一个Optional实例,t必须非空;
Optional.empty(): 创建一个空的Optional实例
Optional…ofNullable(Tt): t可以为null
 
● 判断Optional容器中是否包含对象:
boolean isPresent(): 判断是否包含对象
void ifPresent(Consumer<?super T>consumer): 如果有值,就执行Consumer接口的实现代码,并且该值会作为参数传给它。
 
● 获取Optional容器的对象:
T get(): 如果调用对象包含值,返回该值,否则抛异常
T orElse(T other):如果有值则将其返回,否则返回指定的other对象。
T orElseGet(Supplier<?extends T>other): 如果有值则将其返回,否则返回由Supplier接口实现提供的对象。
T orElseThrow(Supplier<?extends X?exceptionSupplier):如果有值则将其返回,否则抛出由Supplier接口实现提供的异常。

public class test{

    public static void newOptional(){
        // 实例化
        Employee e = new Employee();
        Optional<Employee> optional1 = Optional.of(e);
        Optional<Employee> optional2 = Optional.empty();
        Optional<Employee> optional3 = Optional.ofNullable(e); // return value == null ? empty() : of(value);
    }

    public static String getEmployeeName(Employee employee){
        return employee.getName();
    }

    // 未使用Optional
    public static void t1(){
        Employee e = null;
        if(e != null){
            getEmployeeName(e);
        }
    }

    // 使用Optional
    public static void t2(){
        Employee e = null;
        Optional<Employee> e1 = Optional.ofNullable(e);
        System.out.println(getEmployeeName(e1.orElse(new Employee(1, "12", 34, 23)))); // 如果不为空,返回T other
    }

    public static void main(String[] args) {
        t2();
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

り澄忆秋、

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值