对Map的key跟value进行排序

对Map的key和value进行排序

1.1.  对集合中的key进行排序

1.1.1.   实例:对字符串形式的key进行自然逆序排序

SortMapKey.java

package map;

 

import java.util.Comparator;

import java.util.LinkedHashMap;

import java.util.Map;

import java.util.Set;

import java.util.TreeMap;

 

public class SortMapKey {

 

    public static void main(String[] args) {

 

       Map<String,String> map = new TreeMap<String,String>(new Comparator<String>() {

 

           public int compare(String key1, String key2) {

              

              return key2.compareTo(key1);

              

              }

       });

       

 

 

       //map.put(null, null);

       map.put("aa", null);

       map.put("bb", "123");

       map.put("dd", "456");

       map.put("cc", "789");

 

       Set<String> keySet = map.keySet();

 

       for (String key : keySet) {

           System.out.println(key + ":" + map.get(key));

       }

 

    }

 

}

 


 

输出结果:

dd:456

cc:789

bb:123

aa:null

1.2.  对Map中的value进行排序

1.2.1.   实例:Map中日期格式的值排序

SortMapValue.java

package map;

 

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Comparator;

import java.util.Date;

import java.util.HashMap;

import java.util.Map;

import java.util.Set;

import java.util.TreeMap;

 

publicclass SorMaptValue {

 

    publicstaticvoid main(String[] args) {

       

       Map<String,Date> hashMap = new HashMap<String, Date>();

       

       Calendar calendar = Calendar.getInstance();

       

       calendar.add(Calendar.DATE, -1);

       hashMap.put("昨天", calendar.getTime());

       

       calendar.add(Calendar.DATE, 1);

       hashMap.put("今天", calendar.getTime());

       

 

       calendar.add(Calendar.DATE, 1);

       hashMap.put("明天", calendar.getTime());

       

       SortValueComparator svc = new SortValueComparator(hashMap);

       

       Map<String,Date> map = new TreeMap<String, Date>(svc);

       map.putAll(hashMap);

       

 
       

       Set<String> keySet = map.keySet();

       

       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

       

       for (String key : keySet) {

           System.out.println(key + ":" + sdf.format(hashMap.get(key)));

       }

 

    }

 

}

 

class SortValueComparator implements Comparator<String>{

    

    private Map<String,Date> map ;

    

    public SortValueComparator(Map<String,Date> map) {

       

       this.map = map;

       

    }

 

    publicint compare(String o1, String o2) {

       

       boolean flag = map.get(o1).before(map.get(o2));

       

       if(flag){

           return 1;

       }else{

           

           return -1;

       }

    }

    

}

 


 

运行结果如下:

明天:2015-02-01

今天:2015-01-31

昨天:2015-01-30

 

2楼u022812849昨天 10:29
加油,我也要像楼主那样的干劲,谢谢。
1楼u022812849昨天 20:47
谢谢分享 学习了`(*∩_∩*)′