@Data
@AllArgsConstructor
public class Person {
Integer id;
Integer age;
Integer type;
public static void main(String[] args) {
List<Person> persons = new ArrayList<>();
persons.add(new Person(7, 10, 1));
persons.add(new Person(2, 10, 1));
persons.add(new Person(5, 10, 1));
persons.add(new Person(3, 26, 2));
persons.add(new Person(4, 35, 2));
persons.add(new Person(6, 23, 2));
persons.add(new Person(10, 23, 3));
persons.add(new Person(11, 24, 3));
persons.add(new Person(11, 23, 3));
persons = persons.stream()
.sorted(
Comparator.comparing(Person::getType).reversed()
.thenComparing(Person::getId)
.thenComparing(Comparator.comparing(Person::getAge).reversed())
).collect(Collectors.toList());
System.out.println(JSON.toJSONString(persons));
}
}
上面的代碼,先對 type 降序, 再對 id 升序,最后對 age 降序,輸出結果如下:
persons: [{"age":10,"id":7,"type":1},{"age":10,"id":2,"type":1},{"age":10,"id":5,"type":1},{"age":26,"id":3,"type":2},{"age":35,"id":4,"type":2},{"age":23,"id":6,"type":2},{"age":23,"id":10,"type":3},{"age":24,"id":11,"type":3},{"age":23,"id":11,"type":3}]
result: [{"age":23,"id":10,"type":3},{"age":24,"id":11,"type":3},{"age":23,"id":11,"type":3},{"age":26,"id":3,"type":2},{"age":35,"id":4,"type":2},{"age":23,"id":6,"type":2},{"age":10,"id":2,"type":1},{"age":10,"id":5,"type":1},{"age":10,"id":7,"type":1}]
上面的例子,是以為要輸出原集合和結果集合,所有才用stream做演示,如果僅僅只是需要對串列做排序,可直接用List#sort(Comparator<? super E> c)方法,
站在巨人肩膀上摘蘋果
https://www.jianshu.com/p/f38aeb894e9c
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/66494.html
標籤:Java
