Java中的HashMap是无序的数据结构,如果想要对HashMap中的数据进行排序,可以将其转换为List,然后对List进行排序
Java中的HashMap是无序的数据结构,如果想要对HashMap中的数据进行排序,可以将其转换为List,然后对List进行排序。
下面是一个示例代码:
importjava.util.*;
publicclassSortHashMap{
publicstaticvoidmain(String[]args){
HashMap<String,Integer>hashMap=newHashMap<>();
hashMap.put("Alice",30);
hashMap.put("Bob",20);
hashMap.put("Charlie",25);
List<Map.Entry<String,Integer>>list=newArrayList<>(hashMap.entrySet());
//使用Comparator对List进行排序
Collections.sort(list,newComparator<Map.Entry<String,Integer>>(){
@Override
publicintcompare(Map.Entry<String,Integer>o1,Map.Entry<String,Integer>o2){
returno1.getValue().compareTo(o2.getValue());
}
});
//打印排序后的结果
for(Map.Entry<String,Integer>entry:list){
System.out.println(entry.getKey()+":"+entry.getValue());
}
}
}
在这个示例中,首先将HashMap转换为List,然后使用Comparator对List进行排序,最后打印排序后的结果。
版权声明
本文仅代表作者观点,不代表博信信息网立场。