public static void main(String[] args) { HashMap phone = new HashMap(); phone.put("Apple", 7299); phone.put("Bpple", 3000); phone.put("SAMSUNG", 6000); phone.put("Meizu", 2698); phone.put("Xiaomi", 2400); //key-sort Set set = phone.keySet(); Object[] arr = set.toArray(); Arrays.sort(arr); System.out.println("原hashMap为无序 转set再转array默认排序为按key排序");
for (Object key : arr) { System.out.println(key + ": " + phone.get(key)); } System.out.println(); //value-sort List<Map.Entry<String, Integer>> sortByValueList = new ArrayList<Map.Entry<String, Integer>>(phone.entrySet()); List<Map.Entry<String, Integer>> sortByKeyList = new ArrayList<Map.Entry<String, Integer>>(phone.entrySet()); // 根据hashMap的Value升序排序: // 也等价 Collections.sort(sortByValueList, Map.Entry.comparingByValue()); sortByValueList.sort(Map.Entry.comparingByValue()); // 根据hashMap的Value降序排序: // Collections.sort(sortByValueList, (o1, o2) -> o2.getValue().compareTo(o1.getValue())); //===================================================================== // 根据hashMap的Key排序: // 也等价 Collections.sort(sortByKeyList, Map.Entry.comparingByKey()); sortByKeyList.sort(Map.Entry.comparingByKey()); // 根据hashMap的Value降序排序: // Collections.sort(sortByKeyList, (o1, o2) -> o2.getKey().compareTo(o1.getKey())); // 遍历 System.out.println("按照value升序"); for (int i = 0; i < sortByValueList.size(); i++) { System.out.println(sortByValueList.get(i).getKey() + ": " + sortByValueList.get(i).getValue()); } System.out.println(); System.out.println("按照key升序"); // 遍历 for (Map.Entry<String, Integer> mapping : sortByKeyList) { System.out.println(mapping.getKey() + ": " + mapping.getValue()); } }
原hashMap顺序(默认按照插入时间) Apple: 7299 Bpple: 3000 Meizu: 2698 SAMSUNG: 6000 Xiaomi: 2400 按照value升序 Xiaomi: 2400 Meizu: 2698 Bpple: 3000 SAMSUNG: 6000 Apple: 7299 按照key升序 Apple: 7299 Bpple: 3000 Meizu: 2698 SAMSUNG: 6000 Xiaomi: 2400 Process finished with exit code 0
如果是按照key排序 且key是字符串 自然根据首字母的ASCII码来