gpt4 book ai didi

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

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

我尝试使用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/

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