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); 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 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章