java8对map按value进行排序

mac2024-05-10  7

java8对map按value进行排序## 标题

Map<String,Long> map = tmp.stream().collect(Collectors.groupingBy(a -> a,Collectors.counting())); // ArrayList<Map.Entry<String,Long>> arrayList = new ArrayList<Map.Entry<String, Long>>(map.entrySet()); // // Collections.sort(arrayList, new Comparator<Map.Entry<String, Long>>() { // @Override // public int compare(Map.Entry<String, Long> o1, Map.Entry<String, Long> o2) { // return ((o2.getValue() - o1.getValue() == 0) ? 0 : (o2.getValue() - o1.getValue() > 0) ? 1 : -1); // } // }); // // System.out.println(arrayList.get(0)); Map<String,Long> resMap = new LinkedHashMap<>(); map.entrySet().stream().sorted(Map.Entry.<String,Long>comparingByValue().reversed()) .forEachOrdered(e -> resMap.put(e.getKey(),e.getValue())); System.out.println(resMap.size());``` 先将list中的字符串进行分组统计放入map中,最后对map按照value倒序排序;
最新回复(0)