方法引用使用双冒号 :: 来引用一个方法,可以作为lambda的快捷写法,使得代码更加简洁。
lambda表达式写法:
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
Function<Collection<Integer>, Integer> max = a -> Collections.max(a);
Integer value = max.apply(list);
System.out.println(value);
方法引用写法:
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
Function<Collection<Integer>, Integer> max = Collections::max;
Integer value = max.apply(list);
System.out.println(value);
即 a -> Collections.max(a);可以改写成Collections::max;
以System.out.println(a);为例
lambda表达式写法:
Consumer<String> lambdaConsumer = a -> System.out.println(a);
lambdaConsumer.accept("hello lambda");
方法引用写法:
Consumer<String> consumer = System.out::println;
consumer.accept("hello lambda");
以List的add方法为例
lambda表达式写法:
BiFunction<List<String>, String, Boolean> listBiFunction = (a, b) -> a.add(b);
Supplier<List<String>> listSupplier = () -> new ArrayList<>();
Boolean add = listBiFunction.apply(listSupplier.get(), "lambda");
方法引用写法
BiFunction<List<String>, String, Boolean> listBiFunction = List::add;
Supplier<List<String>> listSupplier = ArrayList::new;
Boolean add = listBiFunction.apply(listSupplier.get(), "lambda");
以List为例
无参构造 public ArrayList()
Supplier<List<String>> noArgsSupplier = ArrayList::new;
List<String> noArgs = listSupplier.get();
有参构造,初始化大小 public ArrayList(int initialCapacity)
Function<Integer, List<Integer>> intArgsFunction = ArrayList::new;
List<Integer> result = intArgsFunction.apply(10);
有参构造,初始化元素 public ArrayList(Collection extends E> c)
List<Integer> integers = Arrays.asList(1, 2, 3);
Function<Collection<Integer>, List<Integer>> collArgsFunction = ArrayList::new;
List<Integer> result = collArgsFunction.apply(integers);