【发布时间】:2013-09-27 21:23:33
【问题描述】:
如何遍历哈希映射以查找前 10 个元素,例如,如果我的映射包含字符串作为键和 int 作为值,我想获取前 10 个具有最大整数的值?
【问题讨论】:
-
到目前为止您尝试过什么?如果您向我们展示您的尝试,那就太好了,这将使我们有机会将您推向正确的方向
如何遍历哈希映射以查找前 10 个元素,例如,如果我的映射包含字符串作为键和 int 作为值,我想获取前 10 个具有最大整数的值?
【问题讨论】:
假设我们有 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);
创建 Guava 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)
【讨论】:
如果是一次性的,您可以通过转换为 List 然后返回 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());
}
【讨论】:
大多数 HashMap 不保留任何顺序,因此您可能需要读取所有键,对它们进行排序,然后从 Hash 中获取相应的值。如果你能告诉我们是什么语言并提供一些示例代码,也许有人可以提供进一步的帮助。
【讨论】: