2013-09-27 190 views
1

如何遍历哈希映射来查找前10个元素,例如,如果我的映射包含字符串作为键和int作为值,我想获取前10个最高整数值?哈希映射迭代

+0

什么你到目前为止尝试过吗?如果你向我们展示你的尝试会很好,它会给我们机会将你推向正确的方向 – Chaos

回答

-1

大多数HashMaps不保留任何类型的顺序,所以您可能需要读取所有的键,对它们进行排序,然后从Hash中获取相应的值。如果你能告诉我们什么语言,并提供一些示例代码,有人可能会进一步帮助。

+0

请仔细阅读,他需要按值排序 – shevchyk

+0

好的,所以同样的逻辑适用。只需要排序值而不是键... – avrono

1

比方说,我们有Map,我们被允许使用外部库 - Guava

Map<String, Integer> map = Maps.newTreeMap(); 
     map.put("A", 13); 
     map.put("B", 11); 
     map.put("C", 27); 
     map.put("D", 38); 
     map.put("E", 25); 
     map.put("F", 12); 
     map.put("G", 25); 
     map.put("D", 35); 
     map.put("H", 28); 
     map.put("R", 13); 
     map.put("N", 24); 
     map.put("T", 37); 

创建番石榴MultiMap从原来map

Multimap<String, Integer> multiMap = ArrayListMultimap.create(); 
     for(String key : map.keySet()){ 
      multiMap.put(key, map.get(key)); 
     } 

multiMap添加条目,并复制到TreeMultiMap

TreeMultimap<Integer, String> reversed = TreeMultimap.create(); 
    Multimaps.invertFrom(multiMap, reversed); 

的条目来创建List并获得前10个元素:

Lists.newArrayList(reversed.entries()).subList(0,10) 
0

如果这是一个一次性的事情,你可以通过转换为一个列表,然后回LinkedHashMap中排序的HashMap:

Map<String, Integer> map = new HashMap<>(); 
    map.put("A", 13); 
    map.put("B", 11); 
    map.put("C", 27); 
    map.put("D", 38); 
    map.put("E", 25); 
    map.put("F", 12); 
    map.put("G", 25); 
    map.put("D", 35); 
    map.put("H", 28); 
    map.put("R", 13); 
    map.put("N", 24); 
    map.put("T", 37); 

    // Take a List copy of the Map 
    List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(map.entrySet()); 

    // Sort the list by the Value 
    Collections.sort(list, new Comparator<Entry<String, Integer>>() { 
     @Override 
     public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) { 
      return (o1.getValue()).compareTo(o2.getValue()); 
     } 
    }); 

    // Create new Map (use LinkedHashMap to maintain order) 
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>(); 
    for (Entry<String, Integer> entry : list) { 
     sortedMap.put(entry.getKey(), entry.getValue()); 
    }