Java 排序集合实现,允许许多相等的值

标签 java collections

我尝试使用TreeSet:

Comparator<Product> pc = (p1, p2) -> ((Double) p1.getPrice()).compareTo(p2.getPrice());
Set<Product> products = new TreeSet<>(pc);
products.add(new Product(10));
products.add(new Product(10));

但问题是,就比较器而言,它不能包含多个相等的值,因此 products 集中只有一个产品。

我需要一些 Collection 实现,它将对新插入的值进行排序,允许许多相等(就比较器而言)值,并且具有插入复杂性 log(n) (可能是基于树的实现)

最佳答案

JDK 中符合您确切要求的PriorityQueue 。来自文档:

An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.

还有

Implementation note: this implementation provides O(log(n)) time for the enqueuing and dequeuing methods (offer, poll, remove() and add); linear time for the remove(Object) and contains(Object) methods; and constant time for the retrieval methods (peek, element, and size).

<小时/>

您还可以继续使用TreeSet,但提供一个Comparator来给出唯一的答案。例如,如果您的产品有一个唯一的名称:

Comparator<Product> pc = Comparator.comparing(Product::getPrice)
                         .thenComparing(Comparator.comparing(Product::getName));

请注意使用 Comparator.comparing 而不是 lambda - 它更简洁、更健壮。

关于Java 排序集合实现,允许许多相等的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42109188/

相关文章:

JAVA - 不允许按住跳跃按钮

java - 为什么 Android 2.2 的模拟器中不出现阿拉伯字符

java - 为什么 Map 不是 "true"集合?

java - 检查未修剪字符串列表是否包含修剪字符串

java - contains() 方法不适用于 java 中的 Arrays.asList

java - 如何解决这个Java数组默认初始化问题

java - 如何在具有自定义标签的 xml 中添加新行?

java - 如何在VisualVM跨平台中获取配置文件选项卡?

java - 实现java集合不丢失信息

TypeScript Set<> 集合通过索引获取值