2010-01-27 42 views
1

移动排序值我有以下TreeMap中:TreeMap的:一个地图的钥匙连同值

TreeMap<Integer, Double> map; 

双值不是唯一的。

我使用Integer键和函数firstEntry()和higherEntry()迭代遍历映射并修改Double值。

现在我想按递减的Double值的顺序列出对的值。 这样做的最好方法是什么?

那些整数键对我很重要,因为Double值不是唯一的,所以我不能有一个Double键。

更新: 更多解释 这是一个经典问题。可以说学生的滚动是关键,他们的百分比就是价值。现在按百分比排序,然后我们应该能够知道它的百分比。因此我需要整数键。

+0

请问什么整数代表什么?知道这将有助于提出,而不是树形图的另一个数据结构... – pgras 2010-01-27 10:16:07

+0

你能澄清的称号?它不清楚你想要分类的领域。 – cmcginty 2012-06-07 02:10:40

回答

1

你可以建立一个TreeSet,可保证插入顺序:

@Test 
public void treeMapSortedByValue() { 
    // given the following map: 
    TreeMap<Integer, Double> map = new TreeMap<Integer, Double>(); 
    map.put(2, Math.E); 
    map.put(1, Math.PI); 
    map.put(3, 42.0); 

    // build a TreeSet of entries 
    Set<Map.Entry<Integer, Double>> sortedEntries = new TreeSet<Map.Entry<Integer, Double>>(new DoubleComparator()); 
    sortedEntries.addAll(map.entrySet()); 

    // optionally you can build a List<Double> with the sorted 
    List<Double> doubles = new LinkedList<Double>(); 
    for (Map.Entry<Integer, Double> entry : sortedEntries) { 
     doubles.add(entry.getValue()); 
    } 
} 

这应该给你:[2.718281828459045, 3.141592653589793, 42.0](注:[Math.E, Math.PI, Math.UNIVERSAL_ANSWER] :-)。

PS

Comparator

class DoubleComparator implements Comparator<Map.Entry<Integer, Double>> { 

    @Override 
    public int compare(Entry<Integer, Double> o1, Entry<Integer, Double> o2) { 
     return Double.compare(o1.getValue(), o2.getValue()); 
    } 
} 
0

您可以做的是:使用entrySet遍历条目。把它们放到一个列表中。然后用正确的比较器对日期进行排序。

+0

他不能,TreeMap只允许唯一的密钥。 – laura 2010-01-27 10:05:08

+0

该死的,noobie错误,我的坏。我会尽力找到另一种解决方案 – 2010-01-27 10:06:30

+0

改变溶液 – 2010-01-27 10:12:10

3

显而易见的解决方案是(通过entrySet然后getValue 可能 - TreeMap类有 values()方法,你可以使用)获得双打的集合,并继续对它们进行排序(使用 Collections.sortArrays.sort) - 但是,这会花费O(n logn)时间。

我不确定你可以用更聪明的方式(==更快)来完成,除非你完全改变数据结构。然而,我发现这种情况发生在另一个数据结构中的唯一方法是在整数和双精度上写一个wrapper,并写两个比较器 - 一个比较integerdouble,然后是integer。您使用的原始TreeMap将是相同的,但您可以从中分离另一个TreeMap,并按第二个比较器进行排序。但是,分离仍然需要O(n logn)时间。