Java Lambda表达式(2) - VS 方法引用
2018-07-11
Coding
Lambda
Java
👋 ‍️‍️阅读
❤️ 喜欢
💬 评论

Java Lambda表达式(2) - VS 方法引用

Method-ref only capture left value

public class Hello {
  String name;
  
  public void say() {
    Thread.sleep(100000);
    System.out.println("Hello " + name);
  }
}

public class Test {
  Hello hello = new Hello("a");
  
  public void sayHelloLater(){
    new Thread(() -> hello.say()).start(); // not sure
    new Thread(hello::say).start(); // print "a"
    hello = new Hello("b");
  }
}

Method-ref has more clear type

list.stream()
  .map
  .flatMap
  .map
  ...
  .reduce((a, b) -> a + b); // which type is this?
  

list.stream()
  .map
  .flatMap
  .map
  ...
  .reduce(Integer::sum);
  .reduce(Long::sum);
  .reduce(String::concat);

Copyright © 2020-2024 Dean Xu. All Rights reserved.