方法引用之其他使用
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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | package com.Lucky.Function; import java.util.ArrayList; import java.util.Collections; import java.util.Locale; import java.util.function.Function; import java.util.function.IntFunction; /* 使用类名引用成员方法 Integer::parseInt 使用数组的构造方法 Integer[]::new */ //要求:将集合的字符串字母大写再输出 public class otherFunction { public static void main(String[] args) { String str= "wdfgnbvcwsdfgh" ; ArrayList<String> list= new ArrayList<>(); Collections.addAll(list, "sdwe" , "dfger" , "wertygh" ); System.out.println( "--匿名内部类写法----" ); list.stream().map( new Function<String, String>() { @Override public String apply(String s) { String s1 = s.toUpperCase(); return s1; } }).forEach(s -> System.out.println(s)); System.out.println( "--lamda写法----" ); list.stream().map( s->s.toUpperCase()).forEach(s -> System.out.println(s)); System.out.println( "--①类名引用成员方法:要根据独有的条件使用----" ); /* public String toUpperCase() { return toUpperCase(Locale.getDefault()); } 疑问点:上面String类的toUpperCase源码,可是为什么明跟抽象方法的形参不一样还可以使用方法引用呢????? 方法引用: 使用条件:1.引用地方要是函数式接口:@FunctionalInterface 2.被引用的方法必须存在 3.被引用的方法的形参以及返回值要跟抽象方法的保持一致【区别在这】 {**** 被引用的方法的形参,需要跟抽象方法的第二个形参开始要保持一致, 如果抽象方法中没有第二个形参,那么被引用方法需要的是无参的成员方法 }**** 4.被引用的方法要满足当前抽象方法的需求 */ list.stream().map(String::toUpperCase).forEach(s -> System.out.println(s)); //////////////////////////////////////////////////////////////////////// System.out.println(); System.out.println( "------------------使用数组的构造方法: 数组的类型要跟流中类型要一致---------------------------" ); //要求:将集合的数据收集到数组中 ArrayList<Integer> intList= new ArrayList<>(); Collections.addAll(intList, 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ); System.out.println( "--- //原始写法:----" ); Integer[] ints = intList.stream().toArray( new IntFunction<Integer[]>() { @Override public Integer[] apply( int value) { return new Integer[value]; } }); for (Integer anInt : ints) { System.out.print(anInt+ "\t" ); } System.out.println(); System.out.println( "--- //方法引用【数组】写法:----" ); Integer[] integers = intList.stream().toArray(Integer[]:: new ); for (Integer an : integers) { System.out.print(an+ "\t" ); } } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律