LinkedHashMap 排序

import  java.util.ArrayList;
import  java.util.Collections;
import  java.util.Comparator;
import  java.util.HashMap;
import  java.util.LinkedHashMap;
import  java.util.List;
import  java.util.Map;
 
public  class  TestMapSortByValue {
 
     public  static  void  main(String[] args) {
         Map map =  new  HashMap();
         map.put( "d" , 4 );
         map.put( "a" , 1 );
         map.put( "c" , 3 );
         map.put( "e" , 5 );
         map.put( "b" , 2 );
         //排序前
         System.out.println( "before sort" );
         for (Map.Entry entry:map.entrySet()){
             System.out.println(entry.getKey()+ "->" +entry.getValue());
         }
         System.out.println();
         
         //将map转成list
         List> infos =  new  ArrayList>(map.entrySet());
         //对list排序,实现新的比较器
         Collections.sort(infos,  new  Comparator>(){
             @Override
             public  int  compare(Map.Entry o1, Map.Entry o2) {
                 return  o1.getValue() - o2.getValue();
             }
         });
         //申明新的有序 map,根据放入的数序排序
         Map lhm =  new  LinkedHashMap();
         //遍历比较过后的map,将结果放到LinkedHashMap
         for (Map.Entry entry:infos){
             lhm.put(entry.getKey(), entry.getValue());
         }
         //遍历LinkedHashMap,打印值
         System.out.println( "after sort" );
         for (Map.Entry entry:lhm.entrySet()){
             System.out.println(entry.getKey()+ "->" +entry.getValue());
         }
     }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
before sort
d->4
e->5
b->2
c->3
a->1
 
after sort
a->1
b->2
c->3
d->4
e->5

你可能感兴趣的:(java)