Lambda表达式-练习前篇
使用Lambda标准格式(无参无返回值)
题目:给定一个厨子Cook接口 内含唯一的抽象方法makFoodd 且无参数 无放回在 使用Lambda的标准格式盗用invokeCooK方法 打印输出“吃饭啦!”字样:
代码
接口
public interface Cook {
    public abstract void makeFood();
}
测试类:
public class test {
    public static void main(String[] args) {
        method(()->{ System.out.println("吃饭啦!"); });
    }
    public static void method(Cook cook){
        cook.makeFood();
    }
}
Lambda的参数和返回值
需求:使用数组存储多个Person对象 对数组中的Person对象使用Arrays的sort方法通过年龄进行升序排序
代码
封装类
public class Person {
    private String name;
    private int age;
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public Person() {
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
测试类:
public static void main(String[] args) {
    //使用数组存储对象
    Person[] arr={
            new Person("张三",20),
            new Person("李四",15),
            new Person("赵六",19)
    };
    //对数组中的person的年龄进行升序排序
  /*  Arrays.sort(arr, new Comparator<Person>() {
        @Override
        public int compare(Person o1, Person o2) {
            return o1.getAge()-o2.getAge();
        }
    });*/
    //使用Lambda的表达式进行排序
    Arrays.sort(arr,(Person o1,Person o2)->{return o1.getAge()-o2.getAge();});
    //遍历数组
    for (Person person : arr) {
        System.out.println(person);
    }
}
运行结果:

 
                    
                 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号