关于java:Java8新特性

3次阅读

共计 10735 个字符,预计需要花费 27 分钟才能阅读完成。

1.Java8 的概述

1.1 Java8 的概述

  • Java8 是 Java 语言的一个重要版本,该版本于 2014 年 3 月公布,是自 Java5 以来最具革命性的版
    本,这个版本蕴含语言、编译器、库、工具和 JVM 等方面的十多个新个性。

2.1 函数式接口

  • 函数式接口次要指只蕴含一个形象办法的接口,如:java.lang.Runnable、java.util.Comparator
    接口等。
  • Java8 提供 @FunctionalInterface 注解来定义函数式接口,若定义的接口不合乎函数式的标准便会
    报错。
  • Java8 中减少了 java.util.function 包,该包蕴含了罕用的函数式接口,具体如下:
接口名称 办法申明 性能介绍
Runnable void run() 既没有参数又没有返回值的办法
Consumer void accept(T t) 依据指定的参数执行操作
Supplier T get() 失去一个返回值
Function<T,R> R apply(T t) 依据指定的参数执行操作并返回
Comparator<T> int compare(T o1, T o2) 比拟
Predicate boolean test(T t) 判断指定的参数是否满足条件

2.1.1 匿名外部类实现函数式接口

/**
 * @Author 振帅
 * @Date 2021/05/31 22:22
 */
public class FunctionalInterfaceTest {public static void main(String[] args) {//1. 匿名外部类:父类 / 接口类型 援用变量名 =  new 父类 / 接口类型(){办法重写}
        Runnable runnable = new Runnable() {
            @Override
            public void run() {System.out.println("我是既没有参数又没有返回值的办法!");
            }
        };
        runnable.run();

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

        Consumer<String> consumer = new Consumer<String>() {
            @Override
            public void accept(String s) {System.out.println("有参但没有返回值的办法" + s);
            }
        };
        consumer.accept("hello world");

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

        Supplier<String> supplier = new Supplier<String>() {
            @Override
            public String get() {return "无参有返回值";}
        };
        System.out.println(supplier.get());

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

        Function<Integer,String> function = new Function<Integer, String>() {
            @Override
            public String apply(Integer integer) {return "有参有返回值" + integer;}
        };
        System.out.println(function.apply(1));

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

        Comparator<Integer> comparator = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {return 0;}
        };
        System.out.println(comparator.compare(1,2));//0

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

        Predicate predicate = new Predicate() {
            @Override
            public boolean test(Object o) {return false;}
        };
        System.out.println(predicate.test("hello"));//false
    }
}

2.1.2 Lambda 表达式实现函数式接口

  • 语法格局:(参数列表) -> {办法体;} – 其中()、参数类型、{} 以及 return 关键字 能够省略。
/**
 * @Author 振帅
 * @Date 2021/05/31 22:22
 */
public class FunctionalInterfaceTest {public static void main(String[] args) {//1. 匿名外部类:父类 / 接口类型 援用变量名 =  new 父类 / 接口类型(){办法重写}
        Runnable runnable = () -> System.out.println("我是既没有参数又没有返回值的办法!");
        runnable.run();

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

        Consumer<String> consumer = s -> System.out.println("有参但没有返回值的办法" + s);
        consumer.accept("hello world");

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

        Supplier<String> supplier = () -> "无参有返回值";
        System.out.println(supplier.get());

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

        Function<Integer,String> function = integer -> "有参有返回值" + integer;
        System.out.println(function.apply(1));

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

        Comparator<Integer> comparator = (o1, o2) -> 0;
        System.out.println(comparator.compare(1,2));//0

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

        Predicate predicate = o -> false;
        System.out.println(predicate.test("hello"));//false
    }
}

2.1.3 办法援用实现函数式接口

  • 办法援用次要指通过办法的名字来指向一个办法而不须要为办法援用提供办法体,该办法的调用交
    给函数式接口执行。
  • 办法援用应用一对冒号 :: 将类或对象与办法名进行连贯,通常应用形式如下:

    • 对象的非静态方法援用 ObjectName :: MethodName
    • 类的静态方法援用 ClassName :: StaticMethodName
    • 类的非静态方法援用 ClassName :: MethodName
    • 结构器的援用 ClassName :: new
    • 数组的援用 TypeName[] :: new
  • 办法援用是在特定场景下 lambda 表达式的一种简化示意,能够进一步简化代码的编写使代码更加
    紧凑简洁,从而缩小冗余代码

(1)对象的非静态方法援用

对象的非静态方法援用 ObjectName :: MethodName

/**
 * @Author 振帅
 * @Date 2021/05/31 23:03
 */
public class MethodReferenceTest {public static void main(String[] args) {Person person = new Person("yangzhen",24);

        //1. 应用匿名外部类的形式通过函数式接口 Runable 中的办法实现对 Person 类中的 show 办法调用
        Runnable runnable = new Runnable() {
            @Override
            public void run() {person.show();
            }
        };
        runnable.run();
        System.out.println("==================================");

        //2. 应用 lambda 表达式的形式实现对 Person 类中的 show 办法调用
        Runnable runnable1 = () -> person.show();
        runnable1.run();
        System.out.println("==================================");

        //3. 应用办法援用的形式对实现对 Person 类中的 show 办法调用
        Runnable runnable2 = person::show;
        runnable2.run();
        System.out.println("==================================");

        //4. 应用匿名外部类的形式通过函数式接口 Consumer 中的办法实现对 Person 类中的 setName 办法调用
        Consumer<String> consumer = new Consumer<String>() {
            @Override
            public void accept(String s) {person.setName(s);
            }
        };
        consumer.accept("yangzhen2");
        System.out.println(person); // yangzhen2 24
        System.out.println("==================================");

        //5. 应用 lambda 表达式的形式实现对 Person 类中的 setName 办法调用
        Consumer<String> consumer1 = s -> person.setName(s);
        consumer.accept("yangzhen3");
        System.out.println(person); // yangzhen3 24
        System.out.println("==================================");

        //6. 应用办法援用的形式对实现对 Person 类中的 setName 办法调用
        Consumer<String> consumer2 = person::setName;
        consumer.accept("yangzhen4");
        System.out.println(person); // yangzhen4 24
    }

}

(2)类的静态方法援用

类的静态方法援用 ClassName :: StaticMethodName

/**
 * @Author 振帅
 * @Date 2021/05/31 23:43
 */
public class MethodReferenceTest {public static void main(String[] args) {

        // 应用匿名外部类的形式通过函数式接口 Comparator 中的办法实现对 Integer 类中的 compare 办法调用
        Comparator<Integer> comparator = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {return Integer.compare(o1,o2);
            }
        };
        System.out.println(comparator.compare(10,20)); //-1

        Comparator<Integer> comparator1 = (o1,o2) -> Integer.compare(o1,o2);
        System.out.println(comparator1.compare(10,20)); //-1

        Comparator<Integer> comparator2 = Integer::compare;
        System.out.println(comparator.compare(20,10)); //1

        // 自定义返回
        Comparator<Integer> comparator3 = (o1, o2) -> {return o1 >= o2 ? o1:o2;};
        System.out.println(comparator3.compare(10,11)); //11
    }

}

(3)类的非静态方法援用

类的非静态方法援用 ClassName :: MethodName

其中一个参数对象作为调用对象来调用办法时, 能够应用上述形式 更形象

/**
 * @Author 振帅
 * @Date 2021/05/31 23:43
 */
public class MethodReferenceTest {public static void main(String[] args) {

        // 应用匿名外部类的形式
        Comparator<Integer> comparator4 = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {return o1.compareTo(o2);
            }
        };
        System.out.println(comparator4.compare(20,10)); //1

        Comparator<Integer> comparator5 = (o1, o2) -> o1.compareTo(o2);
        System.out.println(comparator5.compare(20,10)); //1
        
        // 其中一个参数对象作为调用对象来调用办法时 更形象
        Comparator<Integer> comparator6 = Integer::compareTo;
        System.out.println(comparator6.compare(10,20)); //-1
    }

}

(4)结构器的援用

结构器的援用 ClassName :: new

/**
 * @Author 振帅
 * @Date 2021/05/31 23:43
 */
public class MethodReferenceTest {public static void main(String[] args) {Supplier<Person> supplier = new Supplier<Person>() {
            @Override
            public Person get() {return new Person();
            }
        };
        System.out.println(supplier.get()); //Person{name='null', age=0}

        Supplier<Person> supplier1 = ()-> new Person();
        System.out.println(supplier1.get()); //Person{name='null', age=0}

        Supplier<Person> supplier2 = Person::new;
        System.out.println(supplier2.get()); //Person{name='null', age=0}

        // 有参结构须要应用 BiFunction
    }

}

(4)数组的援用

数组的援用 TypeName[] :: new

/**
 * @Author 振帅
 * @Date 2021/05/31 23:43
 */
public class MethodReferenceTest {public static void main(String[] args) {Function<Integer,Person[]> function = new Function<Integer, Person[]>() {
            @Override
            public Person[] apply(Integer integer) {return new Person[integer];
            }
        };
        System.out.println(Arrays.toString(function.apply(3)));//[null, null, null]

        Function<Integer,Person[]> function1 = integer -> new Person[integer];
        System.out.println(Arrays.toString(function1.apply(4)));//[null, null, null, null]

        Function<Integer,Person[]> function2 = Person[]::new;
        System.out.println(Arrays.toString(function2.apply(5)));//[null, null, null, null, null]
    }

}

2.2 Stream 接口

2.2.1 基本概念

  • java.util.stream.Stream 接口是对汇合性能的加强,能够对汇合元素进行简单的查找、过滤、筛选
    等操作。
  • Stream 接口借助于 Lambda 表达式极大的进步编程效率和程序可读性,同时它提供串行和并行两
    种模式进行汇聚操作,并发模式可能充分利用多核处理器的劣势。

2.2.2 应用步骤

  • 创立 Stream,通过一个数据源来获取一个流。
  • 转换 Stream,每次转换返回一个新的 Stream 对象。
  • 对 Stream 进行聚合操作并产生后果。

2.2.3 创立形式

  • 形式一:通过调用汇合的默认办法来获取流,如:default Stream stream()
  • 形式二:通过数组工具类中的静态方法来获取流,如:static IntStream stream(int[] array)
  • 形式三:通过 Stream 接口的静态方法来获取流,如:static Stream of(T… values)
  • 形式四:通过 Stream 接口的静态方法来获取流,static Stream generate(Supplier<? extends T>
    s)

2.2.4 两头操作

  • 筛选与切片的罕用办法如下:
办法申明 性能介绍
Stream filter(Predicate<? super T> predicate) 返回一个蕴含匹配元素的流
Stream distinct() 返回不蕴含反复元素的流
Stream limit(long maxSize) 返回不超过给定元素数量的流
Stream skip(long n) 返回抛弃前 n 个元素后的流
  • 映射的罕用办法如下:
办法申明 性能介绍
Stream map(Function<? super T,? extends R> mapper) 返回每个解决过元素组成的流
Stream flatMap(Function<? super T,? extends Stream<? extends R>> mapper) 返回每个被替换过元素组成的流,并将所有流合成一个流
  • 排序的罕用办法如下:
办法申明 性能介绍
Stream sorted() 返回通过天然排序后元素组成的流
Stream sorted(Comparator<? super T> comparator) 返回通过比拟器排序后元素组成的流

2.2.5 终止操作

  • 匹配与查找的罕用办法如下:
办法申明 性能介绍
Optional findFirst() 返回该流的第一个元素
boolean allMatch(Predicate<? super T> predicate) 返回所有元素是否匹配
boolean noneMatch(Predicate<? super T> predicate) 返回没有元素是否匹配
Optional max(Comparator<? super T> comparator) 依据比拟器返回最大元素
Optional min(Comparator<? super T> comparator) 依据比拟器返回最小元素
long count() 返回元素的个数
void forEach(Consumer<? super T> action) 对流中每个元素执行操作
  • 规约的罕用办法如下:
办法申明 性能介绍
Optional reduce(BinaryOperator accumulator) 返回联合后的元素值
  • 收集的罕用办法如下:
办法申明 性能介绍
<R,A> R collect(Collector<? super T,A,R> collector) 应用收集器对元素进行解决

2.2.6 代码案例

(1)Stream 流实现汇合元素的过滤和打印

/**
 * @Author 振帅
 * @Date 2021/06/01 0:39
 * 过滤出大于 18 岁的人
 */
public class ListPersonTest {public static void main(String[] args) {

        //1. 筹备一个 List 汇合并放入 Person 类型的对象后打印
        List<Person> list = new LinkedList<>();

        list.add(new Person("AAA",16));
        list.add(new Person("BBB",13));
        list.add(new Person("CCC",22));
        list.add(new Person("DDD",21));
        list.add(new Person("DDD",21));
        list.add(new Person("EEE",30));

        for (Person person : list) {System.out.println(person);
        }

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

        //2. 将 List 汇合中所有成年人过滤出来并放入另外一个汇合中打印
        List<Person> list2 = new LinkedList<>();

        for (Person person : list) {if (person.getAge() >= 18) {list2.add(person);
            }
        }

        for (Person person : list2) {System.out.println(person);
        }

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

        //3. 应用 Stream 接口实现上述性能
        list.stream().filter(new Predicate<Person>() {
            @Override
            public boolean test(Person person) {return person.getAge() >= 18;
            }
        }).forEach(new Consumer<Person>() {
            @Override
            public void accept(Person person) {System.out.println(person);
            }
        });

        System.out.println("==================================");
        //4. 应用 Lambda 表达式对上述代码进行优化
        list.stream().filter(person -> person.getAge() >= 18).forEach(person -> System.out.println(person));

        System.out.println("==================================");
        //5. 应用办法援用
        list.stream().filter(person -> person.getAge() >= 18).forEach(System.out::println);
        
    }
}

(2)Stream 流实现汇合元素的切片和映射

public class ListPersonTest {public static void main(String[] args) {List<Person> list = new LinkedList<>();

        list.add(new Person("AAA",16));
        list.add(new Person("BBB",13));
        list.add(new Person("CCC",22));
        list.add(new Person("DDD",21));
        list.add(new Person("DDD",21));
        list.add(new Person("EEE",30));

        //1. 实现对汇合元素通过流跳过 2 个元素后再取 2 个元素后打印
        list.stream().skip(2).limit(3).forEach(System.out::println);
        
        //2. 实现对汇合中所有元素中的年龄获取并打印
        list.stream().map(new Function<Person, Integer>() {
            @Override
            public Integer apply(Person person) {return person.getAge();
            }
        }).forEach(System.out::println);
        
        list.stream().map(person -> person.getAge()).forEach(System.out::println);
        
        list.stream().map(Person::getAge).forEach(System.out::println);
        
    }
}

(3)Stream 流实现汇合元素排序

public class ListPersonTest {public static void main(String[] args) {List<Person> list = new LinkedList<>();

        list.add(new Person("AAA",16));
        list.add(new Person("BBB",13));
        list.add(new Person("CCC",22));
        list.add(new Person("DDD",21));
        list.add(new Person("DDD",21));
        list.add(new Person("EEE",30));

        list.stream().sorted((p1,p2)-> p1.getAge() - p2.getAge()).forEach(System.out::println);

        list.stream().sorted(Comparator.comparingInt(Person::getAge)).forEach(System.out::println);
        
    }
}
正文完
 0