建立資源類
@Data
@AllArgsConstructor
class Persons{
private Integer id;
private String name;
}
方式1
根據欄位降序排序屬性排序
List<Persons> list1 = new ArrayList<>();
List<Persons> list2 = new ArrayList<>();
list1.add(new Persons(1,"A"));
list1.add(new Persons(7,"B"));
list2.add(new Persons(3,"C"));
list2.add(new Persons(2,"D"));
list1.addAll(list2);
System.out.println(list1);
list1.sort(Comparator.comparing(Persons::getId).reversed());
輸出:
![JAVA裡List集合中的物件根據物件的某個屬性值降序或者升序排序](https://cdn.learnku.com/uploads/images/202202/10/55807/ljTJN1x0hm.png!large)
方式2
自定義排序匿名內部類
Collections.sort(list1, new Comparator<Persons>() {
@Override
public int compare(Persons u1, Persons u2) {
return -(u1.getId() -u2.getId());
}});
System.out.println(list1);
輸出:
[Persons(id=7, name=B), Persons(id=3, name=C), Persons(id=2, name=D), Persons(id=1, name=A)]
方式3
可以實現一個Comparable介面重寫compareTo (不推薦,不靈活)
blog.csdn.net/zolalad/article/deta...
本作品採用《CC 協議》,轉載必須註明作者和本文連結