Java8新特性
layout: post title: “02-26-java8新特性” date: 2019-02-26 12:11:30 +0800
- lambda 和 函数表达式 函数接口 lambda 单函数表达式 单函数接口,并为接口增加注解@FunctionalInterface
lambda示例:
Arrays.asList( "a", "b", "d" ).forEach(System.out::print);
Arrays.asList( "a", "b", "d" ).forEach( e -> System.out.print( e ) );
Arrays.asList( "a", "b", "d" ).forEach( e -> {System.out.print( e );} );
Arrays.asList( "a", "b", "d" ).forEach( ( String e ) -> System.out.print( e ) );
Arrays.asList( "a", "b", "d" ).forEach(new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
});
函数传递
public static boolean isGreenApple( Apple apple )
{
return("green".equals( apple.getColor() ) );
}
public static boolean isHeavyApple( Apple apple )
{
return(apple.getWeight() > 150);
}
public interface Predicate<T>{
boolean test( T t );
}
static List<Apple> filterApples( List<Apple> inventory, Predicate<Apple> p )
{
List<Apple> result = new ArrayList<>();
for ( Apple apple : inventory )
{
if ( p.test( apple ) )
{
result.add( apple );
}
}
return(result);
}
//main
filterApples(inventory, Main::isGreenApple);
- 接口的默认方法和静态方法
```
private interface Defaulable {
// Interfaces now allow default methods, the implementer may or
// may not implement (override) them.
default String notRequired() {
return “Default implementation”;
}
}
private static class DefaultableImpl implements Defaulable { }
private static class OverridableImpl implements Defaulable { @Override public String notRequired() { return “Overridden implementation”; } } private interface DefaulableFactory { // Interfaces now allow static methods static Defaulable create( Supplier< Defaulable > supplier ) { return supplier.get(); } } public static void main( String[] args ) { Defaulable defaulable = DefaulableFactory.create( DefaultableImpl::new ); System.out.println( defaulable.notRequired() );
defaulable = DefaulableFactory.create( OverridableImpl::new );
System.out.println( defaulable.notRequired() ); }
3 方法引用
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() );
} } // 引用的类型是构造器引用 final Car car = Car.create( Car::new ); // 静态方法引用 cars.forEach( Car::collide ); // 成员方法的引用 cars.forEach( Car::repair ); // 实例对象的成员方法的引用 final Car police = Car.create( Car::new ); cars.forEach( police::follow );
4. 加入函数的参数名称
5. Optional进行可非空内容包装
Optional< String > fullName = Optional.ofNullable( null );
System.out.println( "Full Name is set? " + fullName.isPresent() );
System.out.println( "Full Name: " + fullName.orElseGet( () -> "[none]" ) );
System.out.println( fullName.map( s -> "Hey " + s + "!" ).orElse( "Hey Stranger!" ) ); ``` 6. Streams
使流处理更加简单,parallel增加流并行能力
- Date/Time API
优化日期处理能力
- 类依赖分析器:jdeps