[英]Get Hashmap Top 3 Keys
I have a hashmap storing the number of occurrences of character in a text. 我有一个散列图,用于存储文本中字符出现的次数。 I am trying to print out the top 3 occurrences, but it is printing incorrectly. 我正在尝试打印出前三名,但是打印不正确。
int max = 1000000000;
for (int i = 1; i <= 3; i++) {
for (Character key : list.keySet()) {
if (list.get(key) < max) {
max = list.get(key);
System.out.println(i + ": " + key + " " + list.get(key));
break;
}
}
}
With Java 8 you can use the code below(*): 使用Java 8时,可以使用以下代码(*):
List<Entry<Character, Integer>> top3 = map.entrySet().stream()
.sorted(comparing(Entry::getValue, reverseOrder()))
.limit(3)
.collect(toList());
(*) with the following imports: (*)具有以下进口:
import static java.util.Comparator.comparing;
import static java.util.Comparator.reverseOrder;
import static java.util.stream.Collectors.toList;
You could modify your program to this form: 您可以将程序修改为以下形式:
for (int i = 1; i <= 3; i++) {
int max = -1;
Character maxKey = 'a';
for (Character key : list.keySet()) {
if (list.get(key) > max) {
max = list.get(key);
maxKey = key;
}
}
System.out.println(i + ": " + maxKey + " " + max );
list.remove(maxKey);
}
You need to sort your entries by number of occurences and get the top 3: 您需要按出现次数对条目进行排序,并获得前3名:
List<Entry<Character, Integer>> entryList = new ArrayList<>(list.entrySet());
Collections.sort(entryList, new Comparator<Entry<Character, Integer>>(){
@Override
public int compare(Entry<Character, Integer> e1, Entry<Character, Integer> e2) {
return e2.getValue() - e1.getValue(); // descending order
}
});
// now let's get the top 3
List<Character> top3 = new ArrayList<>(3);
for(Entry<Character, Integer> e : entryList) {
top3.add(e.getValue());
if(top3.size() == 3) {
break;
}
}
Here's a solution using Java 8 streams, based on the one provided by @assylias. 这是基于@assylias提供的Java 8流的解决方案。 It performs the complete task of collecting character counts from a String into a Map and selecting the top 3 entries. 它完成将字符串中的字符计数收集到Map中并选择前3个条目的完整任务。
import java.util.ArrayList;
import static java.util.Comparator.*;
import java.util.List;
import java.util.Map.Entry;
import static java.util.stream.Collectors.*;
public class Stream {
public static void main(final String[] args) {
final String text = "hello stackoverflow, let's count these character occurrences!";
final char[] charArray = text.toCharArray();
final List<Character> characters = new ArrayList<Character>(text.length());
for (final char c : charArray) {
characters.add(c);
}
final List<Entry<Character, Long>> top3 = characters.stream()
.collect(groupingBy(Character::charValue, counting()))
.entrySet().stream()
.sorted(comparing(Entry::getValue, reverseOrder())).limit(3).collect(toList());
System.out.println(top3);
}
}
Output: 输出:
[e=8, c=7, =6]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.