Java8新特性全览

参考文章

Java 8 新特性

概述

2014年3月18日发布,这边咱只讨论几个主要的:

  • Lambda表达式 - 允许把函数作为方法的参数。
  • 方法引用 - lambda基础上进一步简化。
  • 默认方法 - 接口里面有实现的方法。
  • Stream API - 将元素集合看作流的一种Java表达的高阶抽象
  • Date Time API - 加强对日期和时间的处理。
  • Optional 类 - 用来解决空指针异常。
  • Nashorn,JavaScript 引擎 - 它允许我们在JVM上运行特定的javascript应用。
  • 新工具 - 新的编译工具。

    1. Lambda 表达式

    Lambda 表达式,也称闭包,Java 8重要特性。 Lambda 允许把函数作为方法的参数。 Lambda 表达式使代码更加简洁。

1.1 Lambda 转化要求

替换参数必须是函数式接口
PS:

  • 函数式接口中只有一个抽象方法。
  • 默认方法有实现,不是抽象方法。
  • 重写超类Object类中public方法不算。
  • @FunctionalInterface 注解表示该类满足函数式接口的要求。

    1.2 Lambda 简单例子

    1. public class Demo{
    2. public static void main(String[] args){
    3. List<String> names1 = new ArrayList<String>();
    4. names1.add("Google ");
    5. names1.add("Runoob ");
    6. names1.add("Taobao ");
    7. names1.add("Baidu ");
    8. names1.add("Sina ");
    9. List<String> names2 = new ArrayList<String>();
    10. names2.add("Google ");
    11. names2.add("Runoob ");
    12. names2.add("Taobao ");
    13. names2.add("Baidu ");
    14. names2.add("Sina ");
    15. // 普通写法
    16. Collections.sort(names1, new Comparator<String>(){
    17. @Override
    18. public int compare(String s1, String s2){
    19. return s1.compareTo(s2);
    20. }
    21. });
    22. System.out.println("普通写法: ");
    23. System.out.println(names1);
    24. // Lambda写法
    25. Collections.sort(name2, (s1, s2) - > s1.compareTo(s2));
    26. System.out.println("Lambda写法: ");
    27. System.out.println(names2);
    28. }
    29. }

    结果

    普通写法: [Baidu , Google , Runoob , Sina , Taobao ] Lambda写法: [Baidu , Google , Runoob , Sina , Taobao ]

2. 方法引用

方法引用 通过方法的名字来指定一个方法。
方法引用 可以简化代码。
方法引用 使用一对冒号::

2.1 方法引用转换要求

  • 方法引用及构造器引用可以理解为lambda的另一种表现形式。
  • 方法引用被调用的方法的参数列表和返回值要与函数式接口中抽象方法参数列表和返回值对应一致。(构造器引用一样)
  • 还有一种情况是,类::实例方法,此情况第一个参数是实例的调用者,第二个参数是实例方法的第二参数。

    2.2 方法引用实例

  1. 对象::实例方法名

    1. @Test
    2. void test1(){
    3. // lambda写法
    4. Consumer<String> con2 = x -> System.out.println(x);
    5. // 方法引用写法
    6. Consumer<String> con2 = System.out::println
    7. }

    Consumer接口

    1. @FunctionalInterface
    2. public interface Consumer<T> {
    3. void accept(T t);
    4. }
  2. 类::静态方法

    1. @Test
    2. void test2(){
    3. // lambda写法
    4. Comparator<Integer> com1 = (x, y) -> Integer.compare(x, y);
    5. // 方法引用写法
    6. Comparator<Integer> com2 = Integer::compare;
    7. }

    Comparator接口

    1. @FunctionalInterface
    2. public interface Consumer<T> {
    3. int compare(T o1, T o2);
    4. }

    Integer的compare方法

    1. public final class Integer extends Number implements Comparable<Integer> {
    2. public static int compare(int x, int y) {
    3. return (x < y) ? -1 : ((x == y) ? 0 : 1);
    4. }
    5. }

    被调用的方法参数列表和返回值类型要与函数式接口的抽象方法参数、返回值保持一致。

  3. 类::实例方法名

    1. @Test
    2. void test3(){
    3. // lambda写法
    4. BiPredicate<String,String> bp = (x,y) -> x.equals(y);
    5. // 方法引用写法
    6. BiPredicate<String,String> bp = String::equals;
    7. // 第一个参数是实例方法的调用者
    8. // 第二个参数的实例方法的第二参数的情况可以这样用
    9. }

    BiPredicate接口

    1. @FunctionalInterface
    2. public interface BiPredicate<T, U> {
    3. boolean test(T t, U u);
    4. }
  4. 构造器引用 类::new

    1. @Test
    2. void test4(){
    3. // lambda写法
    4. Supplier<Person> supplier1 = ()->new Person();
    5. // 构造器引用写法
    6. Supplier<Person> supplier = Person::new;
    7. }

    Supplier接口

    1. @FunctionalInterface
    2. public interface Supplier<T> {
    3. T get();
    4. }

    Person类

    1. @Data
    2. public class Person implements Serializable {
    3. private static final long serialVersionUID = -7008474395345458049L;
    4. private String name;
    5. private int age;
    6. // 调用哪个构造器是函数式接口决定,即Supplier中的get是无参的,所有调无参构造器。
    7. public Person() { }
    8. public Person(String name, int age) {
    9. this.name = name;
    10. this.age = age;
    11. }
    12. }
  5. 数组引用 Type::new

    1. @Test
    2. void test5(){
    3. // lambda写法
    4. Function<Integer,String[]> fun = x -> new String[x];
    5. // 数组引用写法
    6. Function<Integer, String[]> fun = String[]::new;
    7. }

    Function接口部分内容

    1. @FunctionalInterface
    2. public interface Function<T, R> {
    3. R apply(T t);
    4. }

    3. 默认方法

    默认方法就是接口可以有实现方法,而且不需要实现类去实现其方法。 方法名前加default就可以在接口实现默认方法。
    为什么要有这个特性?
    为了解决接口的修改与现有的实现不兼容的问题。

    3.1 语法例子

    1. public interface Vehicle{
    2. default void print(){
    3. System.out.println("我是一辆车!");
    4. }
    5. }

    3.2 多个默认方法

    说明情况:一个类实现了多个接口,且这些接口有相同的默认方法,此情况下解决办法有两个:

    1. public interface Vehicle {
    2. default void print(){
    3. System.out.println("我是一辆车!");
    4. }
    5. }
    6. public interface FourWheeler {
    7. default void print(){
    8. System.out.println("我是一辆四轮车!");
    9. }
    10. }
  6. 自己创建默认方法进行覆盖

    1. public class Car implements VehicleFourWheeler{
    2. default void print(){
    3. System.out.println("我是一辆四轮车");
    4. }
    5. }
  7. 使用super来调用指定接口的默认方法

    1. public class Car implements VehicleFourWheeler{
    2. public void println(){
    3. Vehicle.super.print();
    4. }
    5. }

    3.3 静态默认方法

    Java 8 的另一个特性是接口可以声明并实现静态方法。

    1. public interface Vehicle{
    2. static void blowHorn(){
    3. System.out.println("按喇叭!");
    4. }
    5. }
    1. public class Car implements Vehicle{
    2. public void print(){
    3. Vehicle.blowHorn();
    4. }
    5. }

    调用

    1. public class Test{
    2. public static void main(String[] args){
    3. Vehicle v = new Car();
    4. v.print();
    5. }
    6. }

    结果

    按喇叭!

4. Steam API

流Steam,让你可以以一种声明的方式处理数据。
使代码简洁。

4.1 Stream 介绍

Steam 是一个来自数据源的元素队列,并支持聚合操作

数据源:集合,数组, I/O channel,产生器gengrator等。 聚合操作:类似SQL语句的操作,如 filter,map,reduce,find等

中间操作都会返回流对象本身,有点像建造者模式中的一种。对集合遍历Steam提供了内部迭代,不同于Iterator或for-each的显示外部迭代。

4.2 转换生成流

集合接口有两种方法生成流

  • steam() - 为集合创建串行流
  • parallelSteam() - 为集合创建并行流
    4.3 Steam提供的方法
    forEach : 迭代流中的每个数据。
    1. Random random = new Random();
    2. random.ints().limit(10).forEach(System.out::println);
    map : 映射每个元素到对应的结果
    1. List<Integer> numbers = Arrays.asList(3, 2, 3, 7, 3, 5);
    2. // 获取对应平方数
    3. List<Integer> squaresList = numbers.stream().map.(i -> i*i).distinct().collect(Collectors.toList);

    distinct 过滤重复元素

filter :设置条件,过滤元素

  1. List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
  2. // 获取空字符串的数量
  3. long count = strings.stream().filter(string -> string.isEmpty()).count();

limit : 获取指定数量

  1. Random random = new Random();
  2. random.ints().limit(10).forEach(System.out::println);

sorted : 对流开始排序

  1. Random random = new Random();
  2. random.ints().limit(10.sorted().forEach(System.out::println));

parallelSteam 并行流 : 并行流,多线程处理,非线程安全。

  1. List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
  2. // 获取空字符串的数量
  3. long count = strings.parallelStream().filter(string -> string.isEmpty()).count();

串行流: 适合存在线程安全问题、阻塞任务、重量借任务,需要使用同一事务的逻辑。 并行流:适合没有线程安全问题,较单纯的数据处理任务。

Collectors :实现了很多规约操作,如流转集合,聚合元素。可用于返回列表或字符串

  1. List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
  2. List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
  3. System.out.println("筛选列表: " + filtered); String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
  4. System.out.println("合并字符串: " + mergedString);

统计 :产生统计结果的收集器,主要用于int,double,long等基本类型上。

  1. List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
  2. IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics();
  3. System.out.println("列表中最大的数 : " + stats.getMax());
  4. System.out.println("列表中最小的数 : " + stats.getMin());
  5. System.out.println("所有数之和 : " + stats.getSum());
  6. System.out.println("平均数 : " + stats.getAverage());

5. Date Time API

5.1 本地化日期时间 API

  1. import java.time.LocalDate;
  2. import java.time.LocalTime;
  3. import java.time.LocalDateTime;
  4. import java.time.Month;
  5. public class Java8Tester {
  6. public static void main(String args[]){
  7. Java8Tester java8tester = new Java8Tester();
  8. java8tester.testLocalDateTime();
  9. }
  10. public void testLocalDateTime(){
  11. // 获取当前的日期时间 LocalDateTime
  12. currentTime = LocalDateTime.now();
  13. System.out.println("当前时间: " + currentTime);
  14. LocalDate date1 = currentTime.toLocalDate(); System.out.println("date1: " + date1);
  15. Month month = currentTime.getMonth();
  16. int day = currentTime.getDayOfMonth();
  17. int seconds = currentTime.getSecond();
  18. System.out.println("月: " + month +", 日: " + day +", 秒: " + seconds);
  19. LocalDateTime date2 = currentTime.withDayOfMonth(10).withYear(2012);
  20. System.out.println("date2: " + date2);
  21. // 12 december 2014
  22. LocalDate date3 = LocalDate.of(2014, Month.DECEMBER, 12); System.out.println("date3: " + date3);
  23. // 22 小时 15 分钟
  24. LocalTime date4 = LocalTime.of(22, 15); System.out.println("date4: " + date4);
  25. // 解析字符串
  26. LocalTime date5 = LocalTime.parse("20:15:30"); System.out.println("date5: " + date5); } }

5.2 使用时区的日期时间API

  1. import java.time.ZonedDateTime;
  2. import java.time.ZoneId;
  3. public class Java8Tester {
  4. public static void main(String args[]){
  5. Java8Tester java8tester = new Java8Tester();
  6. java8tester.testZonedDateTime();
  7. }
  8. public void testZonedDateTime(){
  9. // 获取当前时间日期
  10. ZonedDateTime date1 = ZonedDateTime.parse("2015-12-03T10:15:30+05:30[Asia/Shanghai]");
  11. System.out.println("date1: " + date1);
  12. ZoneId id = ZoneId.of("Europe/Paris");
  13. System.out.println("ZoneId: " + id);
  14. ZoneId currentZone = ZoneId.systemDefault();
  15. System.out.println("当期时区: " + currentZone);
  16. }
  17. }

date1: 2015-12-03T10:15:30+08:00[Asia/Shanghai] ZoneId: Europe/Paris 当期时区: Asia/Shanghai

6. Optional 类

可以为null的容器对象。若值存在isPresent()方法,调get()则返回该对象。
用于解决空指针异常。