0

可能重复:
如何对 Java 中的值对 Map<Key, Value> 进行排序?

我有一个 HashMap 如下:

 Key Value
  A    5
  B    3
  C    10
  D    4
  E    1
  F    11

我需要找到价值最高的那个,你建议我怎么做?我应该对它们进行排序并获得第一个还是有其他更快的方法?

4

5 回答 5

3

我不建议对搜索要求进行排序。正如@David Lam 所建议的,您可以执行如下搜索(迭代)以找到最高值的键。

    Set<String> keys = myMap.keySet();
    Iterator<String> keyIter = keys.iterator();
    String highestValueKey = null;
    while(keyIter.hasNext()){
         String key = keyIter.next();
         if(highestValueKey == null){
             highestValueKey = key;
         }else if(myMap.get(key).intValue() > myMap.get(highestValueKey).intValue()){
             highestValueKey = key;
         }
    }

最后,highestValueKey将引用最高值元素的键。

于 2012-10-05T03:59:52.190 回答
2

SortedMap这通过使用 a并传入 aComparator值更容易解决:

final Map<String, Integer> map = new HashMap<String, Integer>();
map.put("A", 5);
map.put("B", 3);
map.put("C", 10);
map.put("D", 4);
map.put("E", 1);
map.put("F", 11);
map.put("G", 11);
map.put("H", 10);

TreeMap<String, Integer> sorted = new TreeMap<String, Integer>(new Comparator<String>() {
  // Note: this comparator imposes orderings that are inconsistent with equals.
  @Override
  public int compare(String a, String b) {
    if (map.get(a) >= map.get(b)) {
      return -1;
    } else {
      return 1;
    } // returning 0 would merge keys
  }
});
sorted.putAll(map);


Entry<String, Integer> first = sorted.firstEntry();
System.out.println("Highest value: " + first.getValue() + is for key: " + first.getKey());

// If duplicate keys are never a concern, you can stop here.  Otherwise, one may 
// continue below to find all keys that may be mapped to an equal highest value:
List<String> others = new LinkedList<String>();
for (Entry<String, Integer> entries : sorted.entrySet()) {
  if (entries.getValue().equals(first.getValue())) {
    others.add(entries.getKey());
  } else {
    break;
  }
}

System.out.println("All keys mapped to this highest value: " + others);

打印出来:

Highest value: 11 is for key: G
All keys mapped to this highest value: [G, F]
于 2012-10-05T04:02:46.727 回答
1

只需遍历键并跟踪最高的 O(n)

于 2012-10-05T03:48:10.877 回答
0

如果你需要经常做“找最大值”的操作,我建议你使用TreeMap

否则,如果您将值插入 HashMap 并对其进行完全控制,则在将值插入HashMap时跟踪最大值。

编辑:您需要以任何一种方式使用 HashMap,如此处所示

于 2012-10-05T03:51:55.327 回答
-2

或者您可以使用冒泡排序找到最高值

于 2012-10-05T03:55:06.317 回答