首页 > 编程语言 >java List排序

java List排序

时间:2022-09-06 14:22:19浏览次数:91  
标签:p2 getAge java List Person p1 new 排序

2.1 新建 Comparator 比较器

List<Person> list = new ArrayList<Person>() {};
Collections.sort(list, new PersonComparator());
class PersonComparator implements Comparator<Person> { @Override public int compare(Person p1, Person p2) { return p2.getAge() - p1.getAge(); } }

2.2 匿名类比较器

      List<Person> list = new ArrayList<Person>() {{
            add(new Person(1, 30, "北京"));
            add(new Person(2, 20, "西安"));
            add(new Person(3, 40, "上海"));
        }};
        // 使用匿名比较器排序
        Collections.sort(list, new Comparator<Person>() {
            @Override
            public int compare(Person p1, Person p2) {
                return p2.getAge() - p1.getAge();
            }
        });

参考:https://blog.csdn.net/sinat_32849897/article/details/122098256

标签:p2,getAge,java,List,Person,p1,new,排序
From: https://www.cnblogs.com/2008nmj/p/16661604.html

相关文章