/** * 按map中的值由高到低排序 * @param map */ private Map<String,Integer> sortMapByValue(Map<String,Integer> map){ Set<Entry<String, Integer>> entrySet = map.entrySet(); List<Map.Entry<String, Integer>> entrySetList = new ArrayList<Map.Entry<String, Integer>>(entrySet); Collections.sort(entrySetList, new MapValueComparator()); Map<String, Integer> resultMap = new LinkedHashMap<String,Integer>(); for(Map.Entry<String, Integer> entry : entrySetList){ resultMap.put(entry.getKey(), entry.getValue()); } return resultMap; } private class MapValueComparator implements Comparator<Map.Entry<String,Integer>>{ @Override public int compare(Entry<String, Integer> entry0, Entry<String, Integer> entry1) { Integer v0 = entry0.getValue(); Integer v1 = entry1.getValue(); return v1.compareTo(v0); } } Map<String,Integer> map =new HashMap<String,Integer>(); map.put("aaa", 1000); map.put("bbb", 500); map.put("ccc", 2000); map.put("ddd", 800); map.put("eee", 1500); Map<String,Integer> map1= new Test().sortMapByValue(map); System.out.println(map1); int N=3; Object[] hobbyFlagKeys = map1.keySet().toArray(); N = Math.min(N, hobbyFlagKeys.length); for(int i=0; i<N; i++){ final String hobbyFlagKey = (String) hobbyFlagKeys[i]; final Integer count = map1.get(hobbyFlagKey); System.out.println(hobbyFlagKey+":::"+count); }
时间: 2024-10-29 11:02:40