Java8新特性

Java 8 :它支持函数式编程,新的 JavaScript 引擎,新的日期 API,新的Stream API 等。

新特性

  • Lambda表达式-Lambda允许把函数作为一个方法的参数(函数作为参数传递进方法中)。
  • 方法引用-方法引用提供了非常有用的语法,可以直接引用已有JAVA类或对象(实例)的方法或构造器。
  • 默认方法-默认方法就是一个在接口里面有了一个实现的方法。
  • Steam API-把真正函数式编程风格引入JAVA。
  • Date Time API-加强对日期与时间的处理。
Lambda

允许把函数作为一个方法的参数(函数作为参数传递进方法中)。

(parameters) -> expression
(parameters) -> {staemenets;}
方法引用

方法引用通过方法的名字来指向一个方法。
方法引用可以使语言的构造更紧凑简洁,减少冗余代码。

public static class Car {
    public static Car create( final Supplier< Car > supplier ) {
        return supplier.get();
    }              

    public static void collide( final Car car ) {
        System.out.println( "Collided " + car.toString() );
    }

    public void follow( final Car another ) {
        System.out.println( "Following the " + another.toString() );
    }

    public void repair() {   
        System.out.println( "Repaired " + this.toString() );
    }
}

构造器引用:语法时Class::new,

final Car car = Car.create(Car::new);
final List<Car> cars = Arrays.asList(car);

静态方法引用:Class::static_method
cars.forEach(Car::collide);

特定类的任意对象的方法引用
cars.forEach(Car::repair);

特定对象的方法引用

final Car police = Car.create(Car::new);
cars.forEach(police::follow);
Stream

Stream 使用一种类似用 SQL 语句从数据库查询数据的直观方式来提供一种对 Java 集合运算和表达的高阶抽象。

集合接口有两个方法生成流:

  • stream()-为集合创建串行流
  • parallelStream()-从名字上看就是 创建并行流

filter

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

sorted

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

并行程序

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// 获取空字符串的数量
int count = strings.parallelStream().filter(string -> string.isEmpty()).count();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值