使用非总排序标准对 java 流进行排序。

Sort a java stream with a non-total ordering criteria.

我正在尝试创建一个对列表进行排序的方法:

private List<Processor> getByPriority(){                        
    return processors.stream().sorted( new ProcessorComparator() ).collect( Collectors.toList() );
}

但我在 Comprator javadoc 中读到,比较需要是总排序关系。也就是说,没有两个比较器可能具有相同的优先级,除非它们相等。情况可能并非如此。

我正在尝试这个简单的比较器:

public class ProcessorComparator implements Comparator<TTYMessageProcessor<?>>{

    @Override
    public int compare( Processor processor1 , Processor processor2 ) {         
        return processor1.getPriority() - processor2.getPriority();
    }       
} 

当然我可以使处理器具有可比性,但我想避免对所有处理器进行修改。有没有办法用流对它们进行排序?作为替代方案,我可以编写自己的方法或创建更复杂的比较器,但令我惊讶的是缺少更优雅的解决方案。

读取references原始流的元素被保留:

Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator.

不会驱逐、删除或复制任何元素。相同的元素从排序中出来,只是重新排序。

编辑:文档还说明 Comparator.compare

It is generally the case, but not strictly required that (compare(x, y)==0) == (x.equals(y)). Generally speaking, any comparator that violates this condition should clearly indicate this fact. The recommended language is "Note: this comparator imposes orderings that are inconsistent with equals."

在地图或集合中使用时,这可能会引起对 equals 的混淆:

Caution should be exercised when using a comparator capable of imposing an ordering inconsistent with equals to order a sorted set (or sorted map). Suppose a sorted set (or sorted map) with an explicit comparator c is used with elements (or keys) drawn from a set S. If the ordering imposed by c on S is inconsistent with equals, the sorted set (or sorted map) will behave "strangely." In particular the sorted set (or sorted map) will violate the general contract for set (or map), which is defined in terms of equals.

如果您将 Comparator 视为键值对的抽象,就会消除混淆:如果键值相等,您不会期望两对相等。这只是意味着这些值中的一些 属性 (即它们的键)被认为是相似的。如果您希望对象 Comparable 以与 equals 一致的方式最好实现同名接口 Comparable.