list 中存放 地图,然后排序

list 中存放 map,然后排序

今天同事遇到一个问题,需要在List中存放Map,每个map只存储一对值。

需要按值排序。

勾起了记忆深处的java 比较器。这玩意不常用,估计很多人都没怎么用过。

觉得有点意思,特意贴出来。

 

Public class Test{

    public void test(){
       List<Map<String,Integer>> list = new ArrayList<Map<String,Integer>>();
	Map<String,Integer> t1 = new HashMap<String,Integer>();
	Map<String,Integer> t2 = new HashMap<String,Integer>();
	Map<String,Integer> t3 = new HashMap<String,Integer>();
	Map<String,Integer> t4 = new HashMap<String,Integer>();
	t1.put("a", 1);
	t2.put("b", 2);
	t3.put("c", 3);
	t4.put("d", 1);
	list.add(t1);
	list.add(t2);
	list.add(t3);
	list.add(t4);
	Collections.sort(list, new MapCompare());
	System.out.println(list);
    }

    private class MapCompare implements Comparator<Map<String,Integer>>{

      public int compare(Map<String,Integer> o1, Map<String,Integer> o2) {
		int value1 = o1.entrySet().iterator().next().getValue();
		int value2 = o2.entrySet().iterator().next().getValue();
		
		return value1-value2;
	}

   }





}