Java 如何根据 HashMap 中的值返回前 10 项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17095083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java How to return top 10 items based on value in a HashMap
提问by Eric
So I am very new to Java and as such I'm fighting my way through an exercise, converting one of my Python programs to Java.
所以我对 Java 非常陌生,因此我正在努力通过练习,将我的一个 Python 程序转换为 Java。
I have run into an issue where I am trying to replicate the behavior, from python the following will return only the keys sorted (by values), not the values:
我遇到了一个问题,我试图复制行为,从 python 中,以下将只返回排序的键(按值),而不是值:
popular_numbers = sorted(number_dict, key = number_dict.get, reverse = True)
In Java, I have done a bit of research and have not yet found an easy enough sample for a n00b such as myself or a comparable method. I have found examples using Guava for sorting, but the sort appears to return a HashMap sorted by key.
在 Java 中,我做了一些研究,但还没有找到一个足够简单的示例,用于像我这样的 n00b 或类似的方法。我找到了使用 Guava 进行排序的示例,但排序似乎返回按键排序的 HashMap。
In addition to the above, one of the other nice things about Python, that I have not found in Java is the ability to, easily, return a subset of the sorted values. In Python I can simply do the following:
除了上述之外,我在 Java 中没有发现的 Python 的其他优点之一是能够轻松返回排序值的子集。在 Python 中,我可以简单地执行以下操作:
print "Top 10 Numbers: %s" % popular_numbers[:10]
In this example, number_dict is a dictionary of key,value pairs where key represents numbers 1..100 and the value is the number of times the number (key) occurs:
在这个例子中,number_dict 是一个键值对的字典,其中键代表数字 1..100,值是数字(键)出现的次数:
for n in numbers:
if not n == '':
number_dict[n] += 1
The end result would be something like:
最终结果将类似于:
Top 10 Numbers: ['27', '11', '5', '8', '16', '25', '1', '24', '32', '20']
前 10 个数字:['27', '11', '5', '8', '16', '25', '1', '24', '32', '20']
To clarify, in Java I have successfully created a HashMap, I have successfully examined numbers and increased the values of the key,value pair. I am now stuck at the sort and return the top 10 numbers (keys) based on value.
澄清一下,在 Java 中我已经成功地创建了一个 HashMap,我已经成功地检查了数字并增加了键值对的值。我现在陷入了排序并根据值返回前 10 个数字(键)。
回答by arshajii
- Put the map's
entrySet()
into aList
. - Sort this list using
Collections.sort
and aComparator
which sortsEntry
s based on their values. - Use the
subList(int, int)
method ofList
to retrieve a new list containing the top 10 elements.
- 将地图
entrySet()
放入一个List
. - 使用
Collections.sort
和 a对这个列表进行Comparator
排序,Entry
根据它们的值对 s进行排序。 - 使用 的
subList(int, int)
方法List
检索包含前 10 个元素的新列表。
Yes, it will be much more verbose than Python :)
是的,它会比 Python 冗长得多:)
回答by i000174
With Java 8+, to get the first 10 elements of a list of intergers:
使用 Java 8+,获取整数列表的前 10 个元素:
list.stream().sorted().limit(10).collect(Collectors.toList());
To get the first 10 elements of a map's keys, that are integers:
要获取地图键的前 10 个元素,即整数:
map.keySet().stream().sorted().limit(10).collect(Collectors.toMap(Function.identity(), map::get));
回答by darijan
Assuming your map is defined something like this and that you want to sort based on values:
假设您的地图定义如下,并且您想根据值进行排序:
HashMap<Integer, Integer> map= new HashMap<Integer, Integer>();
//add values
Collection<Integer> values= map.values();
ArrayList<Integer> list= new ArrayList<Integer>(values);
Collections.sort(list);
Now, print the first top 10 elements of the list.
现在,打印列表的前 10 个元素。
for (int i=0; i<10; i++) {
System.out.println(list.get(i));
}
The values in the map are not actually sorted, because the HashMap
is not sorted at all (it stores the values in the buckets based on the hashCode of the key). This code is just displaying 10 smallest elements in the map.
映射中的值实际上并未排序,因为HashMap
根本未排序(它根据键的 hashCode 将值存储在桶中)。此代码仅显示地图中的 10 个最小元素。
EDITsort without loosing the key-value pairs:
编辑排序而不丢失键值对:
//sorted tree map
TreeMap<Integer, Integer> tree= new TreeMap<>();
//iterate over a map
Iteartor<Integer> it= map.keySet().iterator();
while (it.hasNext()) {
Integer key= it.next();
tree.put(map.get(key), key);
}
Now you have the TreeMap
tree that is sorted and has reversed key-value pairs from the original map, so you don't lose the information.
现在您的TreeMap
树已经排序并从原始映射中反转了键值对,因此您不会丢失信息。
回答by chessbot
HashMap
s aren't ordered in Java, and so there isn't really a good way to order them short of a brute-force search through all the keys. Try using TreeMap
: http://docs.oracle.com/javase/6/docs/api/java/util/TreeMap.html
HashMap
s 不是在 Java 中排序的,因此除了通过所有键进行蛮力搜索之外,并没有真正的好方法来排序它们。尝试使用TreeMap
:http: //docs.oracle.com/javase/6/docs/api/java/util/TreeMap.html
回答by Paul Vargas
Try the next:
尝试下一个:
public static void main(String[] args) {
// Map for store the numbers
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
// Populate the map ...
// Sort by the more popular number
Set<Entry<Integer, Integer>> set = map.entrySet();
List<Entry<Integer, Integer>> list = new ArrayList<>(set);
Collections.sort(list, new Comparator<Entry<Integer, Integer>>() {
@Override
public int compare(Entry<Integer, Integer> a,
Entry<Integer, Integer> b) {
return b.getValue() - a.getValue();
}
});
// Output the top 10 numbers
for (int i = 0; i < 10 && i < list.size(); i++) {
System.out.println(list.get(i));
}
}
回答by Louis Hartmetz
Guava Multisetis a great fit for your use case, and would nicely replace your HashMap. It is a collection which counts the number of occurences of each element.
Guava Multiset非常适合您的用例,并且可以很好地替换您的 HashMap。它是一个计算每个元素出现次数的集合。
Multisets has a method copyHighestCountFirst, which returns an immutable Multiset ordered by count.
Multisets有一个方法copyHighestCountFirst,它返回一个按计数排序的不可变Multiset。
Now some code:
现在一些代码:
Multiset<Integer> counter = HashMultiset.create();
//add Integers
ImmutableMultiset<Integer> sortedCount = Multisets.copyHighestCountFirst(counter);
//iterate through sortedCount as needed
回答by nsfyn55
Use a SortedMap
, call values()
. The docs indicate the following:
使用SortedMap
, 调用values()
。文档指出以下内容:
The collection's iterator returns the values in ascending order of the corresponding keys
The collection's iterator returns the values in ascending order of the corresponding keys
So as long as your comparator is written correctly you can just iterate over the first n
keys
因此,只要您的比较器写入正确,您就可以迭代第一个n
键