[JAVA] java 集合排序多个属性排序方法
java 集合排序多个属性排序方法
sorted 方法
sorted 是对list转换成stream流的方法,不对有有list元素排序,而是返回一个排序后的新list:
如果想第二个排序字段倒序排可以如下写法 thenComparing
如果想倒叙:reversed()
代码:
public class User { private Integer id; private String name; private String address; private Integer age; public User(){ } public User(Integer id, String name, String address, Integer age) { this.id = id; this.name = name; this.address = address; this.age = age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", address='" + address + '\'' + ", age=" + age + '}'; } }
var list = new ArrayList<User>(); list.add(new User(1,"aa","aa",1)); list.add(new User(2,"bb","bb",2)); list.add(new User(3,"aa","cc",2)); list.add(new User(4,"dd","dd",1)); //排序 var ls = list.stream() .sorted(Comparator.comparing(User::getAge,Comparator.nullsLast(Integer::compareTo)) .reversed() .thenComparing(User::getName,Comparator.nullsLast(String::compareTo))) .toList(); for (User l : ls) { System.out.println(l); }
结果: