获取 Hashmap 前 3 个键

Get Hashmap Top 3 Keys

我有一个 hashmap 存储文本中字符出现的次数。我正在尝试打印前 3 次出现的次数,但打印不正确。

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;
        }
    }
}

对于 Java 8 你可以使用下面的代码(*):

List<Entry<Character, Integer>> top3 = map.entrySet().stream()
                                    .sorted(comparing(Entry::getValue, reverseOrder()))
                                    .limit(3)
                                    .collect(toList());

(*) 具有以下导入:
import static java.util.Comparator.comparing;
import static java.util.Comparator.reverseOrder;
import static java.util.stream.Collectors.toList;

您需要按出现次数对条目进行排序并获得前 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;
    }
}

您可以将您的程序修改为这种形式:

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);
}

这是一个使用 Java 8 个流的解决方案,基于@assylias 提供的流。它执行从 String 收集字符计数到 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 Whosebug, 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);
    }
}

输出:

[e=8, c=7,  =6]