Java8 方法引用

2022-08-17  本文已影响0人  Tinyspot

1. 方法引用

2. 常见形式

重点:某个方法签名和接口结构恰好一致

::提取的函数,最主要的区别在于静态与非静态方法,非静态方法比静态方法多一个参数,就是被调用的实例

public static void main(String[] args) {
    // BiFunction<String, Integer, String> biFunction1 = (String str, Integer i) -> str.substring(i);
    BiFunction<String, Integer, String> biFunction2 = (str, i) -> str.substring(i);
    BiFunction<String, Integer, String> biFunction3 = String::substring;

    // String : String substring(int beginIndex)
    String content = "Hello JDK8";

    // 对象::实例方法  Function<T, R> : R apply(T t);
    Function<Integer, String> function = content::substring;
    String result = function.apply(1);

    // 类::实例方法  BiFunction<T, U, R> : R apply(T t, U u);
    BiFunction<String, Integer, String> biFunction = String::substring;
    result = biFunction.apply(content, 1);
}

2.1 对象::实例方法

  Consumer<String> consumer = str -> System.out.println(str);

  // void println(String x) 与 void accept(T t); 结构一样
  PrintStream out = System.out; // 实例
  Consumer<String> method1 = out::println;
        
  Consumer<String> method2 = System.out::println;
  method1.accept("hello");
  Person person = new Person("tinyspot");
  Supplier<String> supplier = () -> person.getName();
  Supplier<String> method = person::getName;
  String name = method.get();

2.2 类::静态方法

  // Comparator<T> : int compare(T o1, T o2);
  // Integer : static int compare(int x, int y)
  Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y);
  Comparator<Integer> method = Integer::compare;

2.3 类::实例方法

若Lambda 的参数列表的第一个参数,是实例方法的调用者,第二个参数(或无参)是实例方法的参数时,格式: 类::实例方法

  // person 作为参数, person.getName()中 person 也是方法的调用者
  Function<Person, String> function = person -> person.getName();
  Function<Person, String> method = Person::getName;
  String apply = method.apply(new Person("tinyspot"));
  System.out.println(apply);
  BiPredicate<String, String> bp1 = (o1, o2) -> o1.equals(o2);
  BiPredicate<String, String> bp2 = String::equals;

3. 构造器引用(类::new)

public static void main(String[] args) {
    Supplier<Person> supplier = () -> new Person();
    Supplier<Person> method = Person::new;
    Person person = method.get();
}

4. 数组引用

Function<Integer, String[]> function = length -> new String[length];
Function<Integer, String[]> method = String[] :: new;
String[] strs = method.apply(10);

5. 其他

List<String> strings = Arrays.asList("222","111");
strings.sort((s1, s2) -> s1.compareToIgnoreCase(s2));
strings.sort(String::compareToIgnoreCase);
// or
Comparator<String> comparator = (String s1, String s2) -> s1.compareToIgnoreCase(s2);
strings.sort(comparator);
上一篇 下一篇

猜你喜欢

热点阅读