java - 在 Java 8 中使用流式链接对集合进行排序

标签 java sorting java-8 comparator java-stream

给定一个类。

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);

尝试按 priceprodName 降序排序列表,然后按 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

排序的列表不符合给定的标准(按priceprodName 降序,按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/

相关文章:

c++ - 基于多个字段搜索大数据集的有效方法

Java 继承 : the strict default-abstract and default-default conflict rules

java - 展平对象并转换为列表

java - 是否可以用 Java 实现 `Functor<T>`?

java - Solr 。奇怪的方面搜索结果

java - 禁止程序输入小于1的数字(if else/switch)

javascript - 按 ID 对图像进行排序

java - 快速排序算法改进

java - 工作经理 : How to return result only when network request is done

java - 是否值得将 <br/> 更改为 <br> 以迁移到 Java 8?