Map根据value排序取topN


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

private static String sort2(Map<String, Integer> map) {
        int limit = 2;
        List<Entry<String, Integer>> topN = new ArrayList<>();
        for (Entry<String, Integer> entry : map.entrySet()) {
            if (topN.size() < limit) {
                topN.add(entry);
            } else {
                int minIndex = 0;
                for (int i = 1; i < limit; i++) {
                    if (topN.get(i).getValue() < topN.get(minIndex).getValue()) {
                        minIndex = i;
                    }
                }
                if (entry.getValue() > topN.get(minIndex).getValue()) {
                    topN.set(minIndex, entry);
                }
            }
        }
        topN.sort((a, b) -> b.getValue() - a.getValue());
        String monthTop2Specs = topN.stream().map(Entry::getKey).collect(Collectors.joining(","));
        return monthTop2Specs;
        //1000000数据 A340689,A630248 共计耗时:110ms
    }
posted @ 2023-10-09 14:07  748573200000  阅读(102)  评论(0编辑  收藏  举报