🌈键盘敲烂,年薪30万🌈

目录
方法引用改写Lambda表达式可简化代码书写,方法引用就是调用已经拥有的方法,学习方法引用是必要的,在java的原码中你会经常看到它,在以后mybatis-plus的学习中会大量使用方法引用。
格式:类名::方法名
代码实现:
- //将集合中的元素转化为int类型并打印
- List
list = new ArrayList<>(); - Collections.addAll(list, "2", "5", "4", "10");
- //Lambda方法
- list.stream().map(new Function
() { - @Override
- public Integer apply(String s) {
- return Integer.parseInt(s);
- }
- }).forEach(System.out::println);*/
- //方法引用
- list.stream().map(Integer::parseInt).forEach(System.out::print);
格式:类名::new
注意:类里面要有对应的构造方法(参数名与抽象方法保持一致)
代码实现:

- //将集合里面的字符串封装称user对象
- //原始写法
- ArrayList
list = new ArrayList<>(); - Collections.addAll(list, "张无忌,18", "小昭,19");
- /*List
collect = list.stream().map(new Function() { - @Override
- public User apply(String s) {
- String[] split = s.split(",");
- return new User(split[0], Integer.parseInt(split[1]));
- }
- }).collect(Collectors.toList());
- System.out.println(collect);*/
- //引用构造方法
- //类名::new
- List
newlist = list.stream().map(User::new).collect(Collectors.toList());
格式:数据类型名[]::new
代码实现:
- //数组的构造方法
- ArrayList
list = new ArrayList<>(); - Collections.addAll(list, 1, 2, 3, 4);
- //原始方法
- Integer[] array = list.stream().toArray(new IntFunction
() { - @Override
- public Integer[] apply(int value) {
- return new Integer[value];
- }
- });
- //方法引用
- Integer[] array1 = list.stream().toArray(Integer[]::new);
格式:this::方法名 (前提:非静态)
注意:被引用方法一定不要是静态的,因为静态里面没有this和super关键字
代码实现:
- //升序排序
- public void testmethod1(){
- List
list = new ArrayList<>(); - Collections.addAll(list, 1, 2, 3, 4, 5);
- // 引用本类中非静态的 this::方法名
- list.stream().sorted(this::method1).forEach(System.out::print);
- }
- public int method1(int o1, int o2){
- return o2 - o1;
- }
格式:super::方法名(前提:非静态)
代码实现:
同上只是将this改为了super
格式:对象名::方法名

- public static void main(String[] args) {
- //将集合中的数据封装成User对象
- //引用其他类型的方法
- ArrayList
list = new ArrayList<>(); - Collections.addAll(list, "张无忌,18", "小昭,19");
- List
newlist = list.stream().map(new Utils()::method).collect(Collectors.toList()); - System.out.println(newlist);
- }
格式:类::方法名
注意:抽象方法的形参从第二个开始到最后与引用方法保持一致,第一个形参用于指明是什么类
代码演示:
- // 将字母转为大写
- //原始方法
- ArrayList
list = new ArrayList<>(); - Collections.addAll(list, "aaa", "bbb", "ccc");
- List
collect = list.stream().map(new Function() { - @Override
- public String apply(String s) {
- return s.toUpperCase();
- }
- }).collect(Collectors.toList());
- System.out.println(collect);
- //方法引用
- //类名::方法名
- //局限:只能引用抽象方法中第一个参数类型里面的方法
- //就像这里只能引用string里面的方法
- //注意 被引用方法的第二个到最后一个形参要与抽象方法保持一致
- List
newlist = list.stream().map(String::toUpperCase).collect(Collectors.toList());
