Java官方笔记9Lambda表达式

Lambda Expression

有了Lambda Expression,就不用再写anonymous classes。

写Lambda,首先要找到它的类型。

There is a restriction on the type of a lambda expression: it has to be a functional interface.

函数接口,只有1个抽象方法的接口:

@FunctionalInterface
public interface Runnable {
    public abstract void run();
}

默认方法do not count,所以下面这个也是函数接口:

@FunctionalInterface
public interface Consumer {

    void accept(T t);

    default Consumer andThen(Consumer after) {
        // the body of this method has been removed
    }
}

静态方法也do not count,所以下面这个还是函数接口:

@FunctionalInterface
public interface Predicate {

    boolean test(T t);

    default Predicate and(Predicate other) {
        // the body of this method has been removed
    }

    default Predicate negate() {
        // the body of this method has been removed
    }

    default Predicate or(Predicate other) {
        // the body of this method has been removed
    }

    static  Predicate isEqual(Object targetRef) {
        // the body of this method has been removed
    }

    static  Predicate not(Predicate target) {
        // the body of this method has been removed
    }
}

接着,实现函数接口的抽象方法,比如Predicate的抽象方法:

boolean test(T t);

实现Predicate

Predicate predicate =
    (String s) -> {
        return s.length() == 3;
    };

省略了返回类型和方法名,只保留参数列表和方法体,用->连接。

再简化:

Predicate predicate = s -> s.length() == 3;

这就是最常见的Lambda,因为前面有String,编译器能够知道,所以这里把(String s)简写为s,然后只有一行,再把大括号和return省略掉。

无return,跟省略掉return:

Consumer print = s -> System.out.println(s);

无参数,用()代替:

Runnable runnable = () -> System.out.println("I am running");

Lambda的使用:

List retainStringsOfLength3(List strings) {

    Predicate predicate = s -> s.length() == 3;
    List stringsOfLength3 = new ArrayList<>();
    for (String s: strings) {
        if (predicate.test(s)) {
            stringsOfLength3.add(s);
        }
    }
    return stringsOfLength3;
}

因为Lambda实现了接口的抽象方法,所以predicate.test(s)调用的实际上是Lambda。

Lambda不能修改变量值:

int calculateTotalPrice(List products) {

    int totalPrice = 0;
    Consumer consumer =
        product -> totalPrice += product.getPrice();  // 编译错误
    for (Product product: products) {
        consumer.accept(product);
    }
}

编译错误:Variable used in lambda expression should be final or effectively final

This process of accessing variable is called capturing: lambdas cannot capture variables, they can only capture values. A final variable is in fact a value.

也就是Lambda只能读,不能写。

使用Lambda

Lambda是JDK8跨时代的语法技术,它引领了大量的JDK API重写。

java.util.function中包含了很多可供实现的函数接口,functional interfaces:

https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/util/function/package-summary.html

比如:

@FunctionalInterface
public interface Supplier {

    T get();
}

Lambda实现:

Supplier supplier = () -> "Hello Duke!";`

使用:

Random random = new Random(314L);
Supplier newRandom = () -> random.nextInt(10);

for (int index = 0; index < 5; index++) {
    System.out.println(newRandom.get() + " ");
}

比如:

List strings = ...; // really any list of any kind of objects
Consumer printer = s -> System.out.println(s);
strings.forEach(printer);

比如:

List immutableStrings =
        List.of("one", "two", "three", "four", "five");
List strings = new ArrayList<>(immutableStrings);
Predicate isOddLength = s -> s.length() % 2 == 0;
strings.removeIf(isOddLength);
System.out.println("strings = " + strings);

比如:

@FunctionalInterface
public interface Function {

    R apply(U u);

    // default and static methods removed
}
Function toLength = s -> s.length();
String word = ...; // any kind of word will do
int length = toLength.apply(word);

以上是JDK中最经典的4种function interface

  • Supplier
  • Consumer
  • Predicate
  • Function

总结一下,Lambda的使用就是先实现function interface的abstract method,然后①接口实例调用abstract method,或者②接口实例被forEach等调用。

Lambda使得function interface能够实例化:Predicate isOddLength = s -> s.length() % 2 == 0;

The java.util.function package is now central in Java, because all the lambda expressions you are going to use in the Collections Framework or the Stream API implement one of the interfaces from that package.

发现没有,把:

List strings = ...; // really any list of any kind of objects
Consumer printer = s -> System.out.println(s);
strings.forEach(printer);

简写一下,去掉中间的接口实例:

List strings = ...; // really any list of any kind of objects
strings.forEach(s -> System.out.println(s));

这不就是常见到的Lambda的形态嘛。换句话说,Lambda的结果就是函数接口实例(Function interface instance),使用Lambda本质上就是调用函数,Java中没有函数的概念,通过function interface的abstract method,引入了函数,从而造就了Lambda。

Method References

Sometimes people call these lambda expressions "anonymous methods", since it is just that: a method that has no name, and that you can move around your application, store in a field or a variable, pass as an argument to a method or a constructor and return from a method.

Consumer printer = s -> System.out.println(s);

这里的Lambda没有什么逻辑,其实就是System.out.println()方法的引用,所以可以简写为Bound(System.out优化前后一致):

Consumer printer = System.out::println;

Static:

IntBinaryOperator max = (a, b) -> Integer.max(a, b);
IntBinaryOperator max = Integer::max;

Unbound(优化前s,优化后String;优化前user,优化后User):

Function toLength = s -> s.length();
Function toLength = String::length;
Function getName = user -> user.getName();
Function toLength = User::getName;
BiFunction indexOf = (sentence, word) -> sentence.indexOf(word);
BiFunction indexOf = String::indexOf;

Constructor:

Supplier> newListOfStrings = () -> new ArrayList<>();
Supplier> newListOfStrings = ArrayList::new;

总结:

Java官方笔记9Lambda表达式_第1张图片

Combining Lambda Expressions

Function interface中的defualt method该登场了。

Predicate nonNull = s -> s != null;
Predicate nonEmpty = s -> s.isEmpty();
Predicate shorterThan5 = s -> s.length() < 5;

Predicate p = nonNull.and(nonEmpty).and(shorterThan5);

这里的and()就是default method,它实现了Lambda的组合,也就是链式调用的既视感。

稍复杂点的:

Predicate isNull = Objects::isNull;
Predicate isEmpty = String::isEmpty;
Predicate isNullOrEmpty = isNull.or(isEmpty);
Predicate isNotNullNorEmpty = isNullOrEmpty.negate();
Predicate shorterThan5 = s -> s.length() < 5;

Predicate p = isNotNullNorEmpty.and(shorterThan5);

Comparators

@FunctionalInterface
public interface Comparator {

    int compare(T o1, T o2);
}

Lambda实现:

Comparator comparator = (i1, i2) -> Integer.compare(i1, i2);
Comparator comparator = Integer::compare;

Comparator的静态方法:

Comparator comparator = Comparator.comparing(String::length);

This comparing() method is a static method of the Comparator interface. It takes a Function as an argument, that should return a type that is an extension of Comparable.

使用:

List users = ...; // this is your list
Comparator byName = Comparator.comparing(User::getName);
users.sort(byName);

还有默认方法thenComparing:

Comparator byFirstNameThenLastName =
        Comparator.comparing(User::getFirstName)
                  .thenComparing(User::getLastName);

参考资料:

Lambda Expressions https://dev.java/learn/lambdas/

你可能感兴趣的:(java,笔记,开发语言)