Map根据value排序取topN

发布时间 2023-10-09 14:13:41作者: SimonHu1993

public static void main(String[] args) {

        Map<String, Integer> map = new HashMap<>();
       /* for (int i = 0; i < 1000000; i++) {
            int nextInt = new Random().nextInt();
            map.put("A" + i, i * nextInt);
        }*/
        map.put("A", 10);
        map.put("B", 5);
        map.put("C", 8);
        map.put("D", 3);
        map.put("E", 12);

        long start = System.currentTimeMillis();
        String top2;
        // top2 = sorted(map);
        top2 = queue(map);

        System.out.println(top2 + " 共计耗时:" + (System.currentTimeMillis() - start) + "ms");

    }

    private static String sorted(Map<String, Integer> map) {
        int limit = 2;
        // 将规格按照value值倒序排序,并取前N位
        Map<String, Integer> topN = map.entrySet().stream().sorted(Entry.<String, Integer>comparingByValue().reversed()).limit(limit)
                .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
        String monthTop2Specs = topN.keySet().stream().collect(Collectors.joining(","));
        return monthTop2Specs;
        //1000000 A665318,A344427 共计耗时:947ms
    }

    private static String queue(Map<String, Integer> map) {
        PriorityQueue<Entry<String, Integer>> pq = new PriorityQueue<>(Comparator.comparingInt(Entry::getValue));
        for (Entry<String, Integer> entry : map.entrySet()) {
            pq.offer(entry);
            if (pq.size() > 2) {
                pq.poll();
            }
        }
        List<Entry<String, Integer>> result = new ArrayList<>(pq);
        result.sort((a, b) -> b.getValue() - a.getValue());
        String top2 = result.stream().map(v -> v.getKey()).collect(Collectors.joining(","));
        return top2;
        //1000000 A923550,A225834 共计耗时:137ms
    }