首页 > 编程语言 > 详细

Java8 HashMap转换为List有序输出(按照Key或Value)

时间:2021-09-06 21:59:48      阅读:19      评论:0      收藏:0      [点我收藏+]
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码来

 

Java8 HashMap转换为List有序输出(按照Key或Value)

原文:https://www.cnblogs.com/TamAlan/p/15232845.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!