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

标签 java sorting java-stream partial-ordering

我正在尝试创建一种通过以下方式对列表进行排序的方法:

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."

当在 map 或集合中使用时,这可能会引起对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 视为键值对的抽象,那么困惑就会消除:如果它们的键相等,您就不会期望两对相等。它只是意味着这些值的某些属性(即它们的键)被认为是相似的。如果您希望对象以与equals一致的方式Comparable,最好实现同名接口(interface)Comparable .

关于java - 使用非总排序标准对 java 流进行排序。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36741444/

相关文章:

java - 找不到JSF文件上传方法

java - 如何使用 BlueJ 编译使用 .jar 文件类的代码?

java - 将值读入从 Java 代码运行的 C 变量

java - 使用 Java Stream 从 ArrayList 中获取最高分

java-8 - 检索映射流所基于的实体的 ID

java - Android:单击列表项后如何使用不同的参数调用 onCreate()?

node.js - 在 NodeJs 中合并一个非常大的列表的最佳方法是什么?

javascript - react.js 按多个值排序对象

javascript - 如何对AJAX请求返回的JSON格式数据进行排序?

java - 使用 lambda 遍历多个嵌套列表