1. 程式人生 > >java中list、list、list排序

java中list、list、list排序


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapListSort {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        List<Map<String,String>> listMap=new ArrayList<>();
        Map<String, String> map1=new HashMap<String, String>();
        map1.put("map001", "001");
        map1.put("map003", "map003");
        map1.put("map002", "map002");
        Map<String, String> map2=new HashMap<String, String>();
        map2.put("map001", "101");
        map2.put("map003", "map303");
        map2.put("map002", "map202");
        //先新增的map2,但是map2中map001的值大於map1中的map001的值。
        listMap.add(map2);
        listMap.add(map1);
        
        for(int i=0;i<listMap.size();i++){
                System.out.print(listMap.get(i).get("map001")+","+listMap.get(i).get("map002")+","+listMap.get(i).get("map003")+"\n");
                
        }
        
        mapSorts(listMap);
        
        System.out.println("\n排序後:");
        for(int i=0;i<listMap.size();i++){
            System.out.print(listMap.get(i).get("map001")+","+listMap.get(i).get("map002")+","+listMap.get(i).get("map003")+"\n");
    }
    }
    
    public static void mapSorts(List<Map<String,String>> map){
        Collections.sort(map,new Comparator<Map<String,String>>() {

            @Override
            public int compare(Map<String, String> o1, Map<String, String> o2) {
                // TODO Auto-generated method stub
                if(o1.get("map001").compareTo(o2.get("map001"))>0){
                    return 1;                   
                }
                return -1;
            }
        });
    }
}