方法引用
使用情景
当要传递给lambda体的操作,已经有实现的方法了,可以使用方法引用。
方法引用也是函数式接口的实例
使用格式 (类(对象):: 方法名)
①对象 :: 非静态方法
②类 :: 静态方法
③类 :: 非静态方法
使用要求
要求接口中的抽象方法的形参列表和返回值类型与方法引用的方法的形参列表和返回值类型相同。(适用情况①②)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | //对象::实例方法 //Consumer中的void accept(T t) //PrintStream中的void println(T t) @Test public void test1(){ Consumer<String> con = s -> System.out.println(s); con.accept( "上海" ); //上海 Consumer<String> con1 = System.out::println; con1.accept( "上海" ); //上海 } //类::静态方法 //Comparator中的int compare(T t1,T t2) //Integer中的int compare(T t1,T t2) @Test public void test2(){ Comparator<Integer> com = (t1, t2) -> Integer.compare(t1,t2); int compare = com.compare( 10 , 11 ); System.out.println(compare); //-1 Comparator<Integer> com1 = Integer::compare; int compare1 = com1.compare( 3 , 1 ); System.out.println(compare1); //1 } //类::实例方法 //Comparator中的int compare(T t1,T t2) //String中的int t1.compareTo(t2),t1调用方法中的参数为t2 @Test public void test3(){ Comparator<String> com = (t1, t2) -> t1.compareTo(t2); int compare = com.compare( "aa" , "ad" ); System.out.println(compare); //-3 Comparator<String> com1 = String :: compareTo; int compare1 = com1.compare( "aa" , "ad" ); System.out.println(compare1); //-3 } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律