對 List<map>內對象進行排序

 

  1. import java.text.ParseException;  
  2. import java.text.SimpleDateFormat;  
  3. import java.util.*;  
  4.   
  5.   
  6. public class Main {  
  7.   
  8.     /** 
  9.      * @param args 
  10.      */  
  11.     public static void main(String[] args) {  
  12.         Map<String,String> map1 = new HashMap<String, String>();  
  13.         map1.put("operationTime""2010-01-10 12:20:00");  
  14.           
  15.         Map<String,String> map2 = new HashMap<String, String>();  
  16.         map2.put("operationTime""2010-01-10 12:40:00");  
  17.           
  18.         Map<String,String> map3 = new HashMap<String, String>();  
  19.         map3.put("operationTime""2010-01-10 12:30:00");  
  20.           
  21.         List<Map<String,String>> list = new ArrayList<Map<String,String>>();  
  22.         list.add(map1);  
  23.         list.add(map2);  
  24.         list.add(map3);  
  25.           
  26.         System.out.println("排序前的list:");  
  27.         System.out.println(list);  
  28.           
  29.         final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  30.         Collections.sort(list, new Comparator<Map<String,String>>(){  
  31.   
  32.             public int compare(Map<String, String> o1, Map<String, String> o2)  
  33.             {  
  34.                 //取出操作時間  
  35.                 int ret = 0;  
  36.                 try  
  37.                 {  
  38.                     ret = df.parse(o1.get("operationTime")).compareTo(df.parse(o2.get("operationTime")));  
  39.                 } catch (ParseException e)  
  40.                 {                     
  41.                     throw new RuntimeException(e);  
  42.                 }  
  43.                 return  ret;  
  44.             }  
  45.               
  46.         });  
  47.           
  48.         System.out.println("排序後的list:");  
  49.         System.out.println(list);  
  50.     }  
  51.   
  52. }  
  53. 轉載地址:http://www.iteye.com/problems/34693
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章