java - 当用于比较对象的所选字段相等时,Java 如何决定对具有多个字段的对象列表进行排序?

标签 java sorting comparator

我有一个名为 Instance 的对象,它有 2 个字段,一个特征数组(这是另一个对象),代表数据集中的列,例如年龄、性别、类别等;以及它们的值(即一个数字)。我还实现了一个自定义比较器,它可以根据实例的特定功能对这些对象的列表进行排序,如下所示:

Comparator<Instance> comparator = Comparator.comparing(c -> c.get(feature));
Instance[] sorted = instList.stream().sorted(comparator).toArray(Instance[]::new);

现在,这段代码工作正常,但是,在很多情况下,我排序所依据的特征与另一个实例具有相同的值。在这种情况下,Java如何决定如何继续对列表进行排序?

最佳答案

从 Java API 中引用 Stream.sorted() :

For ordered streams, the sort is stable. For unordered streams, no stability guarantees are made.

List 上的流是 ordered , 这意味着 stable使用排序算法。稳定排序保证相等的元素不会被交换。比较相等的元素以与起始列表中相同的相对顺序保留。

标准库中的所有排序方法都有类似的保证:

  • Collections.sort()

  • Arrays.sort()

  • Arrays.parallelSort()

    This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

    ...

    The documentation for the methods contained in this class includes briefs description of the implementations. Such descriptions should be regarded as implementation notes, rather than parts of the specification. Implementors should feel free to substitute other algorithms, so long as the specification itself is adhered to. (For example, the algorithm used by sort(Object[]) does not have to be a MergeSort, but it does have to be stable.)

  • List.sort()

    Implementation Note:
    This implementation is a stable, adaptive, iterative mergesort...

关于java - 当用于比较对象的所选字段相等时,Java 如何决定对具有多个字段的对象列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65263483/

相关文章:

java - 按 HashMap 的值(按映射的值比较)对 HashMap 的数组列表进行排序

javascript - 怎么能避免!! JavaScript 中的比较?

java - 如何将php客户端连接到java webservice?

c++ - 这个排序算法的复杂度是多少?

javascript - 根据数组内关联对象的属性对 div 元素进行排序

python - 排序 : How to treat special character greater than alphabetical in Python 2?

java - 如何按属性对自定义对象的 vector (即其他自定义对象的映射)进行排序?

java - Spring日志和用户自定义日志分离

java - Spark-Java静态文件位置问题

java - 抽象类的私有(private)字段不能在子类中访问