程序员社区

(Java集合面试题)如何对Object的list排序

看例子吧,哈哈,这个跟对象排序也是一样的呢~

public class Person {

    private String name;
    private Integer age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}

public class Test {

    public static void main(String[] args) {

        List<Person> list = new ArrayList<>();
        list.add(new Person("jay", 18));
        list.add(new Person("tianLuo", 10));

        list.stream().forEach(p -> System.out.println(p.getName()+" "+p.getAge()));
        // 用comparing比较对象属性
        list.sort(Comparator.comparing(Person::getAge));

        System.out.println("排序后");

        list.stream().forEach(p -> System.out.print(p.getName()+" "+p.getAge()+" "));
    }
}

Java面试题

赞(0) 打赏
未经允许不得转载:IDEA激活码 » (Java集合面试题)如何对Object的list排序

一个分享Java & Python知识的社区