java中List排序 例子
package test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
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 Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自動生成されたメソッド・スタブ
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
Map<String,Object> m1 = new HashMap<String,Object>();
m1.put("NO", 2);
m1.put("NO1", "2");
m1.put("NO2", "f");
list.add(m1);
Map<String,Object> m2 = new HashMap<String,Object>();
m2.put("NO", 1);
m2.put("NO1", "10");
m2.put("NO2", "z");
list.add(m2);
Map<String,Object> m3 = new HashMap<String,Object>();
m3.put("NO", 1);
m3.put("NO1", "10");
m3.put("NO2", "a");
list.add(m3);
Test test = new Test();
test.getSortedList(list,new String[]{"NO","NO1","NO2"});
System.out.println(list);
}
private void getSortedList(List<Map<String, Object>> list, String[] pros) {
if (pros.length <= 0)
return;
for (int i = pros.length - 1; i >= 0; i--) {
final String pro = pros[i];
try {
Collections.sort(list, new Comparator<Map<String, Object>>() {
String name = "get";
Method method = Map.class.getMethod(name, new Class[] {Object.class});
public int compare(Map<String, Object> a, Map<String, Object> b) {
if (a == null || b == null) {
return 0;
} else {
int flag = 0;
try {
Object as = method.invoke(a, new Object[] {pro});
Object bs = method.invoke(b, new Object[] {pro});
if (as == null && bs == null)
return 0;
else if (as == null)
return -1;
else if (bs == null)
return 1;
else {
if (as instanceof Integer) {
Integer va = (Integer) as;
Integer vb = (Integer) bs;
flag = va.compareTo(vb);
}else if (as instanceof String) {
String va = (String) as;
String vb = (String) bs;
flag = va.compareTo(vb);
}
}
} catch (IllegalArgumentException e) {
System.out.println("e1");
} catch (IllegalAccessException e) {
System.out.println("e2");
} catch (InvocationTargetException e) {
System.out.println("e3");
}
return flag;
}
}
});
} catch (NoSuchMethodException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
执行结果:
[{NO=1, NO2=a, NO1=10}, {NO=1, NO2=z, NO1=10}, {NO=2, NO2=f, NO1=2}]