给定一个类。
public class Entity {
private Long id;
private String prodName;
private BigDecimal price;
// Constructors + getters + setters + hashcode() + equals() + toString().
}
构建实体
的列表。
List<Entity> list = new ArrayList<>();
Entity entity = new Entity();
entity.setId(1L);
entity.setProdName("A");
entity.setPrice(new BigDecimal(10));
list.add(entity);
entity = new Entity();
entity.setId(2L);
entity.setProdName("B");
entity.setPrice(new BigDecimal(20));
list.add(entity);
entity = new Entity();
entity.setId(3L);
entity.setProdName("C");
entity.setPrice(new BigDecimal(30));
list.add(entity);
entity = new Entity();
entity.setId(4L);
entity.setProdName("D");
entity.setPrice(new BigDecimal(40));
list.add(entity);
entity = new Entity();
entity.setId(5L);
entity.setProdName("E");
entity.setPrice(new BigDecimal(50));
list.add(entity);
entity = new Entity();
entity.setId(6L);
entity.setProdName("F");
entity.setPrice(new BigDecimal(60));
list.add(entity);
entity = new Entity();
entity.setId(7L);
entity.setProdName("F");
entity.setPrice(new BigDecimal(60));
list.add(entity);
尝试按 price
和 prodName
降序排序列表,然后按 id
升序排序。
Comparator<Entity> comparator = Comparator.comparing(Entity::getPrice).reversed();
comparator = comparator.thenComparing(Entity::getProdName).reversed();
comparator = comparator.thenComparingLong(Entity::getId);
list = list.stream().sorted(comparator).collect(Collectors.toList());
// Or Collections.sort(list, comparator);
list.stream().forEachOrdered(l -> System.out.println(l.getId() + " : " + l.getPrice() + " : " + l.getProdName()));
执行排序后,列表应如下所示。
6 : 60 : F
7 : 60 : F
5 : 50 : E
4 : 40 : D
3 : 30 : C
2 : 20 : B
1 : 10 : A
但是列表,经过排序后,显示如下。
1 : 10 : A
2 : 20 : B
3 : 30 : C
4 : 40 : D
5 : 50 : E
6 : 60 : F
7 : 60 : F
排序的列表不符合给定的标准(按price
和prodName
降序,按id
升序)。
还需要做什么?
最佳答案
每次调用 reversed() 时都会反转整个比较器。相反,只需按照您的描述进行操作即可:
Comparator<Entity> comparator = Comparator.comparing(Entity::getPrice,
Comparator.reverseOrder());
comparator = comparator.thenComparing(Entity::getProdName,
Comparator.reverseOrder());
comparator = comparator.thenComparingLong(Entity::getId);
list = list.stream().sorted(comparator).collect(Collectors.toList());
list.stream().forEachOrdered(l -> System.out.println(l.getId() + " : " + l.getPrice() + " : " + l.getProdName()));
关于java - 在 Java 8 中使用流式链接对集合进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33015274/