HashMap的倒序排序
阿新 • • 發佈:2019-01-06
public class TestShort { public static void main(String[] args) { // 需求:對hashmap的value的值的大小進行逆序排序 // 建立一個HashMap 然後填充資料 HashMap<String, Integer> oldhMap = new HashMap<>(); oldhMap.put("a", 12); oldhMap.put("b", 53); oldhMap.put("c", 41); oldhMap.put("d", 24); HashMap<String, Integer> newMap = sortMap(oldhMap); printMap(oldhMap, newMap); } /** * 對map集合進行逆序排序 * @param oldhMap * @return */ private static HashMap<String, Integer> sortMap(HashMap<String, Integer> oldhMap) { /* * 在 Collections 有個排序的方法 sort(List<T> list, Comparator<? super T> comparator) * 第一個引數為List map無法使用 所以要想辦法把map轉化為List */ //把map轉成Set集合 Set<Entry<String, Integer>> set = oldhMap.entrySet(); //通過set 建立一個 ArrayList 集合 ArrayList<Entry<String, Integer>> arrayList = new ArrayList<>(set); //對arraylist進行倒序排序 Collections.sort(arrayList, new Comparator<Entry<String, Integer>>() { @Override public int compare(Entry<String, Integer> arg0, Entry<String, Integer> arg1) { //逆序 就用後面的引數 - 前面的引數 return arg1.getValue() - arg0.getValue(); } }); //建立一個map LinkedHashMap<String, Integer> map = new LinkedHashMap<>(); for (int i = 0; i < arrayList.size(); i++) { Entry<String, Integer> entry = arrayList.get(i); map.put(entry.getKey(), entry.getValue()); } return map; } /** * 列印map集合 * @param oldhMap 老集合 * @param newMap 排序後的新集合 */ private static void printMap(HashMap<String, Integer> oldhMap, HashMap<String, Integer> newMap) { System.out.println(oldhMap.toString()); System.out.println(oldhMap.toString()); } }