JDK8的新特性1

JDK8的新特性: 1.Default Methods for Interfaces

  1. Lambda exxpressions
  2. 一些常见的Lamdba的使用方式 JDK8的第一个新特性,接口中可以通过default关键字来定义方法的默认行为。
interface Formula {
    double calculate(int a);
    default double sqrt(int a) {
        return Math.sqrt(a);
    }
}
Formula formula = new Formula() {
    @Override
    public double calculate(int a) {
        return sqrt(a * 100);
    }
};

formula.calculate(100);     // 100.0
formula.sqrt(16);// 4.0     

JDK8的第二个特性就是Lambda表达式。为了替换匿名的类,Java8支持了一个更加短的语法糖:lambda表达式。

List<String> names = Arrays.asList("peter", "anna", "mike", "xenia");

Collections.sort(names, new Comparator<String>() {
    @Override
    public int compare(String a, String b) {
        return b.compareTo(a);
    }
});

//lambda 表达式
Collections.sort(names,(String a,String b)->{
  return b.compareTo(a);
});

// lambda short
Collections.sort(names,(String a,String b)-> b.compareTo(a));

//lambda shorter
Collections.sort(names,(a,b)-> b.compareTo(a));

如图所示,那么什么是functional interface? functional interface 函数式接口,当然首先是一个接口,然后就是在这个接口里面只能有一个抽象方法。这种类型的接口也称为SAM接口,即Single Abstract Method interfaces。

1.函数式接口里允许定义默认方法: 2.函数式接口里允许定义静态方法: 3.函数式接口里允许定义java.lang.Object里的public方法,代码类似:

@FunctionalInterface
	interface Converter<F, T> {
	    T convert(F from);
	    boolean equals(Object obj);

	}

4.函数式接口里允许子接口继承多个父接口,但每个父接口中都只能存在一个抽象方法,且必须的相同的抽象方法。代码如下:

interface PConverter1<F, T> {
   T convert(F from);
}

interface PConverter2<F, T> {
   T convert(F from);
}

@FunctionalInterface
interface Converter<F, T> extends PConverter1, PConverter2{
    boolean equals(Object obj);
}

另外,Java 8 enables you to pass references of methods or constructors via the :: keyword. The above example shows how to reference a static method. But we can also reference object methods: Java8 支持:: 操作,代表着一种对方法的调用

//举例1:静态方法的使用
Converter<String, Integer> converter = Integer::valueOf;
Integer converted = converter.convert("123");
System.out.println(converted);   // 123

//举例2:普通方法的使用
class Something {
    String startsWith(String s) {
        return String.valueOf(s.charAt(0));
    }
}
Something something = new Something();
Converter<String, String> converter = something::startsWith;
String converted = converter.convert("Java");
System.out.println(converted);    // "J"

//举例3:new 方法的使用

class Person {
    String firstName;
    Person() {}

    Person(String firstName) {
        this.firstName = firstName;
    }
}

interface PersonFactory<P extends Person> {
    P create(String firstName);
}

//总感觉这样写的话,会被打死!首先省掉了一个匿名的实现PersonFactory的匿名类,然后省掉了匿名类调用create的方法,最终直接写的是create方法的实现,Person的构建方法。

PersonFactory<Person> personFactory = Person::new;
Person person = personFactory.create("Peter");

接触了Lamdba的使用方式,经常会在 Google Guava 的jar中使用的一些常见的lamdba用法如下:

Predicate<String> predicate = (s) -> s.length() > 0;
predicate.test("foo");              // true
predicate.negate().test("foo");     // false
Predicate<Boolean> nonNull = Objects::nonNull;
Predicate<Boolean> isNull = Objects::isNull;
Predicate<String> isEmpty = String::isEmpty;
Predicate<String> isNotEmpty = isEmpty.negate();

Function<String, Integer> toInteger = Integer::valueOf;
Function<String, String> backToString = toInteger.andThen(String::valueOf);
backToString.apply("123");     // "123"


Supplier<Person> personSupplier = Person::new;
personSupplier.get();   // new Person

Consumer<Person> greeter = (p) -> System.out.println("Hello, " + p.firstName);
greeter.accept(new Person("Luke", "Skywalker"));

Comparator<Person> comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName);
Person p1 = new Person("John", "Doe");
Person p2 = new Person("Alice", "Wonderland");
comparator.compare(p1, p2);             // > 0
comparator.reversed().compare(p1, p2);  // < 0


Optional<String> optional = Optional.of("bam");
optional.isPresent();           // true
optional.get();                 // "bam"
optional.orElse("fallback");    // "bam"
optional.ifPresent((s) -> System.out.println(s.charAt(0)));     // "b"

Powered by andiHappy and Theme by AndiHappy