方法引用

关键符号 ::

静态方法引用

类名::静态方法
如果某个Lambda表达式里只是调用一个静态方法,并且前后参数一致,可以使用静态方法引用

public class test {
    public static void main(String[] args) {

       People [] p = new People[]{new People(12,"ccc"),
               new People(14,"dsf"),new People(9,"peo")};
//     1  Arrays.sort(p, new Comparator<People>() {
//           @Override
//           public int compare(People o1, People o2) {
//                return o1.getAge() -o2.getAge();
//
//           }
//       });


//     2   Arrays.sort(p, (People o1, People o2) -> {return o1.getAge() -o2.getAge();});


//      3 Arrays.sort(p, ( o1,  o2) ->  o1.getAge() -o2.getAge());



//        Arrays.sort(p,(o1,o2)->cmp.Cmp(o1,o2));
        Arrays.sort(p, cmp::Cmp);
        System.out.println(Arrays.toString(p));

    }
}

实例方法引用

对象名::实例方法
如果某个Lambda表达式里只是调用一个实例方法,并且前后参数一致,可以使用实例方法引用

public class test {
    public static void main(String[] args) {

       People [] p = new People[]{new People(12,"ccc"),
               new People(14,"dsf"),new People(9,"peo")};
        cmp cm = new cmp();
        Arrays.sort(p, cm::Cmp);
        System.out.println(Arrays.toString(p));

    }
}

特定类型的方法引用

类型::方法
如果某个lambda表达式里只是调用一个实例方法,并且前面参数列表中的第一个参数作为方法的主调,后面的所有参数都是作为该实例方法的入参的,则此时就可以使用特定类型的方法引用。

public class test {
    public static void main(String[] args) {

        String [] p =new String[]{"acd","def","DF","Andy"};
//        Arrays.sort(p, new Comparator<String>() {
//            @Override
//            public int compare(String o1, String o2) {
//                return o1.compareToIgnoreCase(o2);
//            }
//        });
//        Arrays.sort(p, (o1, o2) -> o1.compareToIgnoreCase(o2));
        Arrays.sort(p, String::compareToIgnoreCase);
        System.out.println(Arrays.toString(p));

    }
}

构造器引用

类名::new
如果某个lambda表达式只是在创建对象,并且前后参数一致,就可以使用构造器引用。

public class test {
    public static void main(String[] args) {
//    CreatPeople cp = new CreatPeople() {
//        @Override
//        public People creat(int age, String name) {
//            return new People(age ,name);
//        }
//    };
       // CreatPeople cp =( age, name) -> new People(age ,name);
        CreatPeople cp = People::new;

    People p = cp.creat(12,"acx");
        System.out.println(p);
    }
}
interface CreatPeople{
     People creat(int age , String name);
}
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值