//Java 实现多字段排序
HashMap<Object,Object> map1 = new HashMap<Object,Object>();
map1.put("dataindex0", null);map1.put("dataindex1", 6);map1.put("dataindex2", 1.1);map1.put("id", 1);
HashMap<Object,Object> map2 = new HashMap<Object,Object>();
map2.put("dataindex0", "2017-12-01");map2.put("dataindex1", 5);map2.put("dataindex2", 1.2);map2.put("id", 2);
HashMap<Object,Object> map3 = new HashMap<Object,Object>();
map3.put("dataindex0", "2017-12-02");map3.put("dataindex1", 7);map3.put("dataindex2", 2.3);map3.put("id", 3);
HashMap<Object,Object> map4 = new HashMap<Object,Object>();
map4.put("dataindex0", "2017-12-02");map4.put("dataindex1", 7);map4.put("dataindex2", 3);map4.put("id", 4);
HashMap<Object,Object> map5 = new HashMap<Object,Object>();
map5.put("dataindex0", "2017-12-03");map5.put("dataindex1", null);map5.put("dataindex2", 9.1);map5.put("id", 5);
HashMap<Object,Object> map6 = new HashMap<Object,Object>();
map6.put("dataindex0", "2017-12-03");map6.put("dataindex1", 3);map6.put("dataindex2", 8.1);map6.put("id", 6);
List<Map<Object,Object>> list = new ArrayList<Map<Object,Object>>();
list.add(map6);list.add(map1);list.add(map5);list.add(map4);list.add(map2);list.add(map3);
// System.out.println("Before Sort: " + list);
final String[] orderByCols = {"dataindex0","dataindex1","dataindex2"};
// final String[] orderByCols = {"dataindex0","dataindex1"};
// final String[] orderByCols = {"dataindex0"};
//Mannual OrderBy
Collections.sort(list,new Comparator<Map>() {
@Override
public int compare(Map o1, Map o2) {
return recursion(o1, o2, 0);
}
private int recursion(Map o1, Map o2, int i) {
if (o1.containsKey(orderByCols[i]) && o2.containsKey(orderByCols[i])) {
Object value1 = o1.get(orderByCols[i]);
Object value2 = o2.get(orderByCols[i]);
if (value1 == null && value2 == null) {
if ((i+1) < orderByCols.length) {
int recursion = recursion(o1, o2, i+1);
return recursion;
}else{
return 0;
}
}else if(value1 == null && value2 != null){
return 1;
}else if(value1 != null && value2 == null){
return -1;
}else{
if (value1.equals(value2)) {
if ((i+1) < orderByCols.length) {
return recursion(o1, o2, i+1);
}else{
return 0;
}
}else{
if (value1 instanceof String && value2 instanceof String) {
return value1.toString().compareTo(value2.toString());
}else{
return new BigDecimal(value1.toString()).compareTo(new BigDecimal(value2.toString()));
}
}
}
}else{
System.out.println(" ** The current map do not containskey : " + orderByCols[i] + ",or The value of key is null **");
return 0;
}
}
});