Lambda表达式之方法的引用

以下都是示例
public class Syntax3 {
    public static void main(String[] args) {
        //方法引用
        //可以快速的将一个lambda表达式的实现指向一个已经实现的方法.
        //语法: 方法的隶属者 :: 方法名
        //注意:
        //1. 参数数量和类型一定要和接口中定义的方法一致
        //2. 返回值的类型也要和接口定义的方法一致
        LambdaSingleReturnSingleParameter lambda = a -> change(a);
        lambda.test(10);    //20

        LambdaSingleReturnSingleParameter lambda2 = Syntax3::change;
        int result = lambda2.test(10);  //20
    }

    private static int change(int a){
        return a*2;
    }
}

构造方法的引用

person类
public class Person {

    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
        System.out.println("有参构造执行了");
    }

    public Person() {
        System.out.println("无参构造执行了");
    }
}
引用
public class Syntax4 {
    public static void main(String[] args) {
        //一般用法
        PersonCreate create = () -> new Person();
        create.getPerson();
        //构造方法的引用
        PersonCreate create1 = Person::new;
        create1.getPerson();

        PersonCreate2 create2 = Person::new;
        create2.getPerson("Jim", 20);
    }

    /**
     * 无参person
     */
    interface PersonCreate{
        Person getPerson();
    }

    /**
     * 有参person
     */
    interface PersonCreate2{
        Person getPerson(String name, int age);
    }
}

集合的排序

public class Example {
    public static void main(String[] args) {
        ArrayList<Person> people = new ArrayList<>();
        people.add(new Person("小明", 10));
        people.add(new Person("小嘎", 13));
        people.add(new Person("小红", 9));
        people.add(new Person("小强", 6));
        people.add(new Person("老王", 27));
        people.add(new Person("老表", 28));

        people.sort(((o1, o2) -> o2.age -o1.age));
        System.out.println(people);
    }
}

TreeSet的排序

public class Example2 {
    public static void main(String[] args) {
        //TreeSet排序
        //使用Lambda表达式来实现Compare接口,实例化TreeSet, 否则TreeSet不知道排序规则,会报错
        TreeSet<Person> set = new TreeSet<Person>((o1,o2) -> {
            if(o2.age >= o1.age){
                return -1;
            }else{
                return 1;
            }
        });
        set.add(new Person("小明", 10));
        set.add(new Person("小嘎", 13));
        set.add(new Person("小红", 9));
        set.add(new Person("小强", 6));
        set.add(new Person("老王", 27));
        set.add(new Person("老表", 28));
        System.out.println(set);
    }
}

猜你喜欢

转载自www.cnblogs.com/shansm/p/12547561.html