从 HashMap 中获取 k 个最高值

Hyd*_*xis 3 java iterator hashmap

在我在下面发布的代码中,我需要从 HashMap 中删除重复项(最高字母值保留在映射中)并在删除重复项后打印k 个最高值的键。我该怎么做呢?我尝试使用 HashSet 但我很无能为力。

public ArrayList<String> mostOften(int k)
    {
        ArrayList<String> lista = new ArrayList<String>();
        HashMap<String,Integer> temp = new HashMap<String, Integer>();

        for(String it : wordList)
        {
            if(temp.containsKey(it))
                temp.put(it, temp.get(it)+1);
            else
                temp.put(it, 1);
        }

        temp = sortByValues(temp);

        Set<Integer> set = new HashSet<Integer>(temp.values());
        System.out.println(set);

        return lista;
    }

    private static HashMap sortByValues(HashMap map) 
    { 
        List list = new LinkedList(map.entrySet());
        Collections.sort(list, new Comparator() 
                         {
                             public int compare(Object o1, Object o2) 
                             {
                                 return ((Comparable)((Map.Entry) (o1)).getValue()).compareTo(((Map.Entry) (o2)).getValue());
                             }
                         });

        HashMap sortedHashMap = new LinkedHashMap();
        for (Iterator it = list.iterator(); it.hasNext();) 
        {
            Map.Entry entry = (Map.Entry) it.next();
            sortedHashMap.put(entry.getKey(), entry.getValue());
        } 
        return sortedHashMap;
    }
Run Code Online (Sandbox Code Playgroud)

Pet*_*rey 6

如果您正在尝试对单词进行频率计数,那么您就走错了路。Java 8 可以更轻松、更简洁地做到这一点。

你需要这些进口

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
Run Code Online (Sandbox Code Playgroud)

编码

public static void main(String[] args) {
    printTopWords(Arrays.asList("Hello World Hello , Bye World".split(" ")), 2);
}

public static void printTopWords(List<String> words, int limit) {
    // using the Stream API
    words.stream()
            // create a map of words with the count of those words
            .collect(Collectors.groupingBy(w -> w, Collectors.counting()))
            // take that map as a stream of entries
            .entrySet().stream()
            // sort them by count in reverse order
            .sorted(Comparator.comparing(Map.Entry<String, Long>::getValue).reversed())
            // limit the number to get top Strings
            .limit(limit)
            // keep just the key ie. drop the count.
            .map(Map.Entry::getKey)
            // print them
            .forEach(System.out::println);
}
Run Code Online (Sandbox Code Playgroud)

印刷

Hello
World
Run Code Online (Sandbox Code Playgroud)