JDK新特性-Lambda表达式的神操作 (3)

对象方法引用: 抽象方法的第一个参数类型刚好是实例方法的类型,抽象方法剩余的参数恰好可以当做实例方法的参数。如果函数式接口的实现能由上面说的实例方法调用来实现的话,那么就可以使用对象方法引用

/** @Author mxn * @Description //TODO 对象方法引用 * @Date 14:26 2020/11/7 * @Param * @return **/ public class Test4 { public static void main(String[] args) { Consumer<Too> c1 = (too)->new Too().foo(); c1.accept(new Too());//输出 foo Consumer<Too> c2 = (Too too) ->new Too2().foo(); c2.accept(new Too());//输出 foo---too2 Consumer<Too> c3 = Too::foo; c3.accept(new Too());//输出 foo BiConsumer<Too2,String> bc = (too2,str)->new Too2().show(str); BiConsumer<Too2,String> bc2 = Too2::show; bc.accept(new Too2(),"abc"); bc2.accept(new Too2(),"def"); BiFunction<Exec,String,Integer> bf1 = (e,s)->new Exec().test(s); bf1.apply(new Exec(),"abc"); BiFunction<Exec,String,Integer> bf2 = Exec::test; bf2.apply(new Exec(),"def"); } } class Exec{ public int test(String name){ return 1; } } class Too{ public Integer fun(String s){ return 1; } public void foo(){ System.out.println("foo"); } } class Too2{ public Integer fun(String s){ return 1; } public void foo(){ System.out.println("foo---too2"); } public void show(String str){ System.out.println("show ---too2"+str); } } 7.5 构造方法引用

构造方法引用: 如果函数式接口的实现恰好可以通过调用一个类的构造方法来实现,那么就可以使用构造方法引用

/** @Author mxn * @Description //TODO 构造方法引用 * @Date 14:27 2020/11/7 * @Param * @return **/ public class Test5 { public static void main(String[] args) { Supplier<Person> s1 = ()->new Person(); s1.get();//输出 调用无参的构造方法 Supplier<Person> s2 = Person::new; s2.get();//输出 调用无参的构造方法 Supplier<List> s3 = ArrayList::new; Supplier<Set> s4 = HashSet::new; Supplier<Thread> s5 = Thread::new; Supplier<String> s6 = String::new; Consumer<Integer> c1 = (age)->new Account(age); Consumer<Integer> c2 = Account::new; c1.accept(123);// 输出 age 参数构造123 c2.accept(456);//输出 age 参数构造456 Function<String,Account> f1 = (str)->new Account(str); Function<String,Account> f2 = Account::new; f1.apply("abc");//输出 str 参数构造abc f2.apply("def");//输出 str 参数构造def } } class Account{ public Account(){ System.out.println("调用无参构造方法"); } public Account(int age){ System.out.println("age 参数构造" +age); } public Account(String str){ System.out.println("str 参数构造" +str); } } class Person{ public Person(){ System.out.println("调用无参的构造方法"); } } 八、小结

JAVA 8 引入 Lambda表达式是接收了函数式编程语言的思想,和指令式编程相比,函数式编程强调函数的计算比指令的执行重要。

lambda表达式可以使代码看起来简洁,但一定程度上增加了代码的可读性以及调试的复杂性,所以在使用时应尽量是团队都熟悉使用,要么干脆就别用,不然维护起来是件较痛苦的事,今天的小知识就到这里了,有问题的小伙伴可以在下方进行留言,大家加油!

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wsfxzd.html