Java8新特性

函数式接口

首先是一个接口,这个接口里抽象方法只能有一个(这种类型的接口也称为SAM接口,即Single Abstract Method Interface),函数式接口也是接口,可以有静态方法和默认方法,只是限制了抽象方法,并且在接口上有@FunctionalInterface注解。

函数式接口主要用在Lambda表达式和方法引用。

函数式接口举栗:
java.lang.Runnable、java.util.concurrent.Callable、java.util.Comparator,java.util.function包下的接口,如Consumer、Predicate、Supplier等

Lambda 表达式

Lambda表达式并不能取代所有的匿名内部类,只能用来取代**函数接口(Functional Interface)**的简写。允许把函数作为一个方法的参数。举栗:

//1.8之前一般使用匿名内部类写法
new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println("running...");
    }
}).start();

//Lambda表达式,不带参
new Thread(()->  System.out.println("running...")).start();

//匿名内部类写法
list.sort(new Comparator() {
    @Override
    public int compare(Object o1, Object o2) {
        return -1;
    }
});

//Lambda表达式,带参
list.sort((s1, s2)-> s1-s2);

方法引用

可以直接引用已有Java类或对象的方法或构造器。与lambda联合使用,方法引用可以使语言的构造更紧凑简洁,减少冗余代码。

使用::引用方法名称来指向一个方法。举栗:

public class Test {
    public void test() {
        //使用方法引用会变成一个函数接口,比如`User::new`
        List<User> list = Arrays.asList(User.create(User::new));
        list.forEach(User::doprint);
    }
}

public class User {
    public static User create(Supplier<User> supplier) {
        return supplier.get();
    }
    
    public static void doprint(User user) {
        System.out.println(user);
    }
}

Stream API

流Stream,可以以一种声明的方式处理数据。举栗:

List<Product> list = Arrays.asList(product1, product2, product3, product4);
// map方法用于映射每个元素到对应的结果
List doublePrices = list.stream().map(product -> product.getPrice() * 2).collect(Collectors.toList());

// filter方法用于通过设置的条件过滤出元素
List filterList = list.stream().filter(product -> product.getPrice() > 3).collect(Collectors.toList());

// sorted、skip、limit方法用于对流进行排序,跳过指定数量,获取指定数量
// Comparator.comparingDouble静态方法,传入一个函数式接口,可以用Lambda简写
List limitProduct = list.stream().sorted(Comparator.comparingDouble(p->-p.getPrice())).skip(2).limit(2).collect(Collectors.toList());

// count方法用于统计数量
long count = list.stream().count();

// distinct方法用于集合元素去重
List<Product> distinctList = list.stream().distinct().collect(Collectors.toList());

// parallel方法是并行操作,返回一个Stream流
Stream<Student> parallelStream = list.stream().parallel();

// findFirst方法用于返回第一个,在并行方案中也不会更改
// findAny方法用于返回任意一个。在非并行操作中,它很可能返回Stream中的第一个元素,但不保证这一点;为了在处理并行操作时获得最佳性能,也无法返回确定结果
Optional<Product> option = list.stream().findFirst();
Optional<Product> option = list.stream().findAny();

// allMatch、anyMatch、noneMatch方法用于对元素匹配校验
boolean allMatch = list.stream().allMatch(product -> product.getPrice() > 3);
boolean anyMatch = list.stream().anyMatch(product -> product.getPrice() > 3);
boolean noneMatch = list.stream().noneMatch(product -> product.getPrice() > 3);

Collectors

Collectors包含许多常见的聚合操作,元素收集、分组、最小值、最大值等操作

List<Product> list = Arrays.asList(product1, product2, product3, product4);
// toList返回List集合,toSet和toList用法一样,toSet返回的是Set集合
List doublePrices = list.stream().map(product -> product.getPrice() * 2).collect(Collectors.toList());

// toMap
Map map = list.stream().collect(Collectors.toMap(Product::getName, Product::getPrice));

// groupingBy,以下两种写法结果相同
//Map map = list.stream().collect(Collectors.groupingBy(pro-> pro.getPrice()));
Map map = list.stream().collect(Collectors.groupingBy(Product::getPrice));

// minBy,以下两种写法结果相同,这里的price是int类型
//Product minPro = list.stream().collect(Collectors.minBy((p1,p2)->((Product) p1).getPrice() - ((Product) p2).getPrice())).get();
Product minPro = list.stream().collect(Collectors.minBy(Comparator.comparing(Product::getPrice))).get();

Optional

Optional是个容器,Optional提供方法,包括判断是否为null等等,可以不用显式进行空值检测,很好的解决空指针异常

User user = null;
Optional<User> optional = Optional.ofNullable(user);
System.out.println(optional.isPresent()); //值存在返回true,否则返回false
System.out.println(optional.get()); //返回值,如果值不存在则报错:NoSuchElementException
System.out.println(optional.orElse(new User("1", "zhangsan"))); //返回值,如果值不存在则返回参数

默认方法

在接口中可以定义默认方法,默认方法是有方法体。接口实现类不需要实现默认方法,在此之前如果接口添加新方法,必须在所有接口实现类中实现新方法,所以引进了默认方法,目的是解决接口的修改与现有的实现不兼容问题。

Date Time

LocalDate localDate = LocalDate.now(); // 2019-05-26
LocalTime localTime = LocalTime.now(); // 17:29:04.436
LocalDateTime localDateTime = LocalDateTime.now(); // 2019-05-26T17:29:04.437
String string = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); //2019-05-26 17:29:04
ZonedDateTime zonedDateTime = ZonedDateTime.now(); // 2019-05-26T17:29:04.438+08:00[GMT+08:00]

欢迎小伙伴们积极指正和讨论,一起共同成长。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值