方法引用就是通过类名或方法名引用已经存在的方法来简化lambda表达式。那么什么时候需要用方法引用呢?如果lamdba体中的内容已经有方法实现了,我们就可以使用方法引用。
lamdba写法:
1@Test
2void test1(){
3 Consumer<String> con = x -> System.out.println(x);
4}方法引用写法:
1@Test
2void test2(){
3 PrintStream out = System.out;
4 Consumer<String> con = out::println;
5}consumer接口:
1@FunctionalInterface
2public interface Consumer<T> {
3 void accept(T t);
4}注意:被调用的方法的参数列表和返回值类型需要与函数式接口中抽象方法的参数列表和返回值类型要一致。
lamdba写法:
1@Test
2void test3(){
3 Comparator<Integer> com = (x, y) -> Integer.compare(x,y);
4}方法引用写法:
1@Test
2void test4(){
3 Comparator<Integer> com = Integer::compare;
4}Comparator接口:
1@FunctionalInterface
2public interface Comparator<T> {
3 int compare(T o1, T o2);
4}Integer类部分内容:
1public final class Integer extends Number implements Comparable<Integer> {
2 public static int compare(int x, int y) {
3 return (x < y) ? -1 : ((x == y) ? 0 : 1);
4 }
5}注意:被调用的方法的参数列表和返回值类型需要与函数式接口中抽象方法的参数列表和返回值类型要一致。
lamdba写法:
1@Test
2void test5(){
3
4 BiPredicate<String,String> bp = (x,y) -> x.equals(y);
5}方法引用写法:
1@Test
2void test6(){
3 BiPredicate<String,String> bp = String::equals;
4}BiPredicate接口:
1@FunctionalInterface
2public interface BiPredicate<T, U> {
3 boolean test(T t, U u);
4}注意:第一个参数是这个实例方法的调用者,第二个参数是这个实例方法的参数时,就可以使用这种语法。
lamdba写法:
1@Test
2void test7(){
3 Supplier<Person> supplier = ()->new Person();
4}构造器应用写法:
1@Test
2void test8(){
3 Supplier<Person> supplier = Person::new;
4}Supplier接口:
1@FunctionalInterface
2public interface Supplier<T> {
3 T get();
4}Person类:
1@Data
2public class Person implements Serializable {
3 private static final long serialVersionUID = -7008474395345458049L;
4
5 private String name;
6 private int age;
7
8 public Person() {
9 }
10 public Person(String name, int age) {
11 this.name = name;
12 this.age = age;
13 }
14}注意:person类中有两个构造器,要调用哪个构造器是函数式接口决定的,也就是Supplier接口中的get()方法是无参的,那么就调用的是person中的无参构造器。
lamdba写法:
1@Test
2void test9(){
3 Function<Integer,String[]> fun = x -> new String[x];
4}数组引用写法:
1@Test
2void test10(){
3 Function<Integer, String[]> fun = String[]::new;
4}Function接口部分内容:
1@FunctionalInterface
2public interface Function<T, R> {
3 R apply(T t);
4}< END >