MAP集合按需排序

   在编程的过程中,有时会遇到需要对MAP集合进行排序的现象,比如像下面这种情况:

List<Map<String,Object>> l = new ArrayList<Map<String,Object>>();
Map<String, Object> ma = new HashMap<String,Object>();
ma.put("num", 22);
ma.put("cc", "cc");
l.add(ma);
ma = new HashMap<String,Object>();
ma.put("num", 33);
ma.put("cc", "dd");
l.add(ma);


   现在需要对集合L中的MAP对象按KEY值‘num'的大小进行排序,经查,现有的API中的Collections.sort方法不支持MAP类的集合排序,怎么办呢,自己写个排序类,实现Comparator接口的compare方法即可,简单的CODE如下:
class SortMap implements Comparator{
	
	private String sortName = null;
	private String compareType = "int";
	public SortMap(String sortName,String compareType){
		this.sortName = sortName;
		this.compareType = compareType;
	}

	@Override
	public int compare(Object o1, Object o2) {
		Map m1 = (Map)o1;
		Map m2 = (Map)o2;
		if(compareType.equalsIgnoreCase("int")){
			Integer ia = (Integer)m1.get(sortName);
			Integer ib = (Integer)m2.get(sortName);
			return ia.compareTo(ib);
		}else{
			String ia = (String)m1.get(sortName);
			String ib = (String)m2.get(sortName);
			return ia.compareTo(ib);
		}
	}
	
}

 
   好了,我们再来写个测试类,

public class TestMapSort<T> {

	@SuppressWarnings("unchecked")
	public void sort(){
		
		List<Map<String,Object>> l = new ArrayList<Map<String,Object>>();
		Map<String, Object> ma = new HashMap<String,Object>();
		ma.put("num", 22);
		ma.put("cc", "cc");
		l.add(ma);
		ma = new HashMap<String,Object>();
		ma.put("num", 33);
		ma.put("cc", "dd");
		l.add(ma);
		
		ma = new HashMap<String,Object>();
		ma.put("num", 11);
		ma.put("cc", "aaa");
		l.add(ma);
		
		ma = new HashMap<String,Object>();
		ma.put("num", 10);
		ma.put("cc", "bbbb");
		l.add(ma);

		SortMap sm = new SortMap("num","int");
		Collections.sort(l,sm);
		for(Map<String,Object> m : l){
			System.out.println("---------each map-----------");
			Set<Map.Entry<String, Object>>  st = m.entrySet();
			for(Entry<String, Object> entry : st){
				 System.out.print("key: "+entry.getKey() +"    ");  
			     System.out.println(entry.getValue());
			}
		}
		
	}
	
	public static void main(String[] arg){
		TestMapSort ts = new TestMapSort();
		ts.sort();
	}
	
}



运行结果如下:
---------each map-----------
key: num    10
key: cc    bbbb
---------each map-----------
key: num    11
key: cc    aaa
---------each map-----------
key: num    22
key: cc    cc
---------each map-----------
key: num    33
key: cc    dd



你可能感兴趣的:(map)