- HashMap存储每对键和值作为一个Entry
Map<String,Integer> map=new HashMap<String,Integer>();
2.创建一个简单的HashMap,并插入一些键和值。
map.put("张三", 80);
map.put("李四", 90);
map.put("王五", 70);
3.从HashMap恢复entry集合,如下所示。
Set<Entry<String,Integer>> array=map.entrySet();
4.从上述mapEntries创建LinkedList。我们将排序这个链表来解决顺序问题。我们之所以要使用链表来实现这个目的,是因为在链表中插入元素比数组列表更快。
List<Entry<String,Integer>> list=new LinkedList<Entry<String,Integer>>(array);
5.通过传递链表和自定义比较器来使用Collections.sort()方法排序链表。
Collections.sort(list,new Comparator<Entry<String,Integer>>(){
public int compare(Entry<String,Integer> o1,Entry<String,Integer> o2){
return o1.getValue().compareTo(o2.getValue());
}
});
6.得到排序后list之后,可以通过LinkedHashmap存储键和值信息对到新的映射中。由于HashMap不保持顺序,因此我们要使用LinkedHashMap。
完整代码如下:
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class sortMapByValues {
public static void main(String[] args){
Map<String,Integer> map=new HashMap<String,Integer>();
map.put("张三", 80);
map.put("李四", 90);
map.put("王五", 70);
System.out.println("排序之前:");
Set<Entry<String,Integer>> array=map.entrySet();
for(Entry<String,Integer> temp:array){
System.out.println(temp.getKey()+" "+temp.getValue());
}
List<Entry<String,Integer>> list=new LinkedList<Entry<String,Integer>>(array);
Collections.sort(list,new Comparator<Entry<String,Integer>>(){
public int compare(Entry<String,Integer> o1,Entry<String,Integer> o2){
return o1.getValue().compareTo(o2.getValue());
}
});
System.out.println("排序之前:");
for(Entry<String,Integer> temp:list){
System.out.println(temp.getKey()+" "+temp.getValue());
}
}
}