簡體   English   中英

從HashMap獲取k個最大值

[英]Get k highest values from 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;
    }

如果您嘗試對單詞進行頻次計數,那么您將走錯路。 Java 8做到了這一點更加輕松和整潔。

您需要這些進口

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

編碼

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

版畫

Hello
World

如果您不熟悉Java 8流和lambda,則以下答案將對您有所幫助:

public class Java7Way {

public static void main(String[] args) {
    Map<String, Integer> myMap = new HashMap<>();
    myMap.put("A", 20);
    myMap.put("A", 38);
    myMap.put("B", 40);
    myMap.put("K", 23);
    System.out.println(sortByValue(myMap,2).toString());
}

public static <K, V extends Comparable<? super V>> Map<K, V>
        sortByValue(Map<K, V> map,int limit) {
    List<Map.Entry<K, V>> list
            = new LinkedList<>(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
        @Override
        public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
            return (o1.getValue()).compareTo(o2.getValue());
        }
    }
            .reversed()//to arrange it in decending order
    );
    Map<K, V> result = new LinkedHashMap<>();//maintains the order which the entries were put into the map
    for (Map.Entry<K, V> entry : list) {
        if (limit == 0) {
            break;
        }
        result.put(entry.getKey(), entry.getValue());
        limit--;
    }
    return result;
}

}

輸出:

{B=40, A=38}

我建議使用Apache Commons Collection中的 TreeBidiMap 在此結構中,所有鍵和所有值均根據鍵和值的類的自然順序進行排序。

對於您的代碼:

    BidiMap<String,Integer> temp = new TreeBidiMap<String, Integer>();
    for(String it : wordList)
    {
        if(temp.containsKey(it))
            temp.put(it, temp.get(it)+1);
        else
            temp.put(it, 1);
    }

    // print values unsing natural sorting in reverse order          
    BidiMap inverse = temp.inverseBidiMap();
    for (MapIterator it = inverse.mapIterator(); it.hasPrevious();) {
       String k = it.next();
       Integer s = it.getValue();  
       System.out.printLn(s + " = " + k);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM