gpt4 book ai didi

java - 如何对使用 Guava Range 值作为键的集合进行排序?

转载 作者:行者123 更新时间:2023-11-30 02:51:31 25 4
gpt4 key购买 nike

我有以下 map ,其中 Range<Integer>是关键:

| Range<Integer> | Set<Range<BigDecimal>>
------------------------------------------------------------
| 1..100 | [0.01..1.00], [2.01..15.00], [1.01..2.00]
------------------------------------------------------------
| 151..250 | [0.01..1.00], [2.01..15.00], [1.01..2.00]
------------------------------------------------------------
| 101..150 | [1.01..7.00], [0.01..1.00]
------------------------------------------------------------

我还有以下比较器实现:

public class RangeComparator<T extends Comparable<T>> implements Comparator<Range<T>> {

@Override
public int compare(Range<T> first, Range<T> second) {
int comparatorResult = first.lowerEndpoint().compareTo(second.lowerEndpoint());
return comparatorResult == 0 ? first.upperEndpoint().compareTo(second.upperEndpoint()) : comparatorResult;
}
}

我想使用这个比较器对 map 中的值进行排序,然后对 map 本身进行排序,从而得到以下结果:

| Range<Integer> | Set<Range<BigDecimal>>
------------------------------------------------------------
| 1..100 | [0.01..1.00], [1.01..2.00], [2.01..15.00]
------------------------------------------------------------
| 101..150 | [0.01..1.00], [1.01..7.00]
------------------------------------------------------------
| 151..250 | [0.01..1.00], [1.01..2.00], [2.01..15.00]
------------------------------------------------------------

Guava Range 类是最终类,并且没有实现 Comparable。

我可以在不手动排序的情况下对其进行排序吗?如果是这样,怎么办?

最佳答案

使用 TreeMap 的构造函数和 TreeSet它采用 Comparator 作为参数,例如

public TreeMap(Comparator<? super K> comparator)

Constructs a new, empty tree map, ordered according to the given comparator.

请注意,没有限制 TreeMap 的键或 TreeSet 的条目需要实现 Comparable

关于java - 如何对使用 Guava Range 值作为键的集合进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38500736/

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