gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 10:01:57 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com