Java8 HashMap轉換為List有序輸出(按照Key或Value)


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碼來

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM