Lambda Exercise 2: There are parameters and return values

Requirements:
Use an array to store multiple Person objects
. Use the Arrays method to sort the Person objects in the array in ascending order by age.

Code :

package demo05.Lambda;

import java.util.Arrays;
import java.util.Comparator;
public class Demo01Arrays {
    
    
    public static void main(String[] args) {
    
    
        //使用数组存储多个Person对象
        Person[] arr = {
    
    
                new Person("赵丽颖",31),
                new Person("杨幂",32),
                new Person("关晓彤",23),
                new Person("胡歌",37),
        };

        //对数组中的Person对象使用Arrays的sort方法通过年龄进行升序(前边-后边)排序
       /* 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 p:arr) {
    
    
            System.out.println(p);
        }
    }
}

Code demo :
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44664432/article/details/107974916