簡體   English   中英

如何獲得 HashMap 中的 3 個最高值?

[英]How to get the 3 highest values in a HashMap?

我有一個 hashmap 如下:

    HashMap<String, Integer> hm = new HashMap<String, Integer>;
    hm.put("a", 1);
    hm.put("b", 12);
    hm.put("c", 53);
    hm.put("d", 2);
    hm.put("e", 17);
    hm.put("f", 8);
    hm.put("g", 8);

我將如何獲得具有 3 個最高值的鍵? 所以它會返回:

    "c", "e", "b"

謝謝。

我的解決方案,按值排序並獲得前 3 名並返回鍵列表。

List<String> keys = hm.entrySet().stream().sorted(Map.Entry.<String, Integer>comparingByValue().reversed()).limit(3).map(Map.Entry::getKey).collect(Collectors.toList());

希望能幫助到你

這很難閱讀,但會表現得更好:

 public static List<String> firstN(Map<String, Integer> map, int n) {
    PriorityQueue<Entry<String, Integer>> pq = new PriorityQueue<>(
        n + 1, Map.Entry.comparingByValue()
    );

    int bound = n + 1;
    for (Entry<String, Integer> en : map.entrySet()) {
        pq.offer(en);
        if (pq.size() == bound) {
            pq.poll();
        }
    }

    int i = n;
    String[] array = new String[n];
    while (--i >= 0) {
        array[i] = pq.remove().getKey();
    }
    return Arrays.asList(array);
}

如果您知道PriorityQueue是如何工作的,那么這很簡單:它在任何給定時間點只保留n + 1元素。 隨着元素的添加,最小的元素被一個接一個地刪除。

完成后,我們將元素插入到數組中,但順序相反(因為PriorityQueue僅對其頭部進行排序,或者根據Comparator頭部始終為最大/最小值)。

您甚至可以將其設為通用,或為此創建帶有流的自定義收集器。

這是我的看法:它只跟蹤 TreeSet 中的前 n 個項目。

import java.util.*;
import java.util.stream.Collectors;

public class TopN {
    public static <E> Collection<E> topN(Iterable<E> values, Comparator<? super E> comparator, int n) {
        NavigableSet<E> result = new TreeSet<>(comparator.reversed());
        for (E value : values) {
            result.add(value);
            if (result.size() > n) {
                result.remove(result.last());
            }
        }
        return result;
    }

    public static void main(String[] args) {
        Map<String, Integer> hm = Map.of(
                "a", 1,
                "b", 12,
                "c", 53,
                "d", 2,
                "e", 17,
                "f", 8,
                "g", 8);

        List<String> result = topN(hm.entrySet(), Map.Entry.comparingByValue(), 3)
                .stream()
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
        System.out.println(result);
    }
}

最終的 output 是[c, e, b]

暫無
暫無

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

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