我尝试使用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()
andadd
); linear time for theremove(Object)
andcontains(Object)
methods; and constant time for the retrieval methods (peek
,element
, andsize
).
您还可以继续使用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/