Collections.sort()排序和map排序方法
Collections.sort()排序和map排序方法:
/** * map排序 * @param rankTimesMap * @return */ private HashMap<String, Integer> hashMapSort(Map<String, Integer> rankTimesMap, final Map<String, Integer> rankCountMap){ // 按顺序保存rankTimesMap中的元素,使用LinkedList类型 List<Map.Entry<String, Integer>> keyList = new LinkedList<Map.Entry<String, Integer>>(rankTimesMap.entrySet()); // 按照上榜次数降序的规则排序 Collections.sort(keyList, new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { if (o2.getValue().compareTo(o1.getValue()) > 0){ return 1; } else if(o2.getValue().compareTo(o1.getValue()) < 0){ return -1; } else { // 如果上榜次数相同,按照名次之和升序排序 Integer rankCountO1 = rankCountMap.get(o1.getKey()); Integer rankCountO2 = rankCountMap.get(o2.getKey()); if (rankCountO1.compareTo(rankCountO2) > 0) { return 1; } else if (rankCountO1.compareTo(rankCountO2) < 0) { return -1; } else { return 0; } } } }); // 将LinkedList按照排序好的结果,存入到HashMap中 HashMap<String,Integer> result = new LinkedHashMap<>(); for(Map.Entry<String, Integer> entry : keyList){ result.put(entry.getKey(), entry.getValue()); } return result; }
随笔看心情