循环遍历按其中某个中文字段排序
/**
* 中文排序
* @author itmyhome
*
*/
public class MapComparator implements Comparator<Map<String, Object>> {
@Override
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
// TODO Auto-generated method stub
String b1 = (String)o1.get("NAME");
String b2 = (String)o2.get("NAME");
Collator cmp = Collator.getInstance(java.util.Locale.CHINA);
if (cmp.compare(b1, b2)>0){
return 1;
}else if (cmp.compare(b1, b2)<0){
return -1;
}
return 0;
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> map1 = new HashMap<String, Object>();
Map<String, Object> map2 = new HashMap<String, Object>();
Map<String, Object> map3 = new HashMap<String, Object>();
Map<String, Object> map4 = new HashMap<String, Object>();
Map<String, Object> map5 = new HashMap<String, Object>();
map1.put("NAME", "朱元璋");
map2.put("NAME", "常遇春");
map3.put("NAME", "张无忌");
map4.put("NAME", "郭靖");
map5.put("NAME", "洪七公");
list.add(map1);list.add(map2);list.add(map3);list.add(map4);list.add(map5);
System.out.println("***排序前***");
for(Map<String, Object> map:list){
System.out.println(map.get("NAME"));
}
System.out.println("***排序后***");
Collections.sort(list, new MapComparator());
for(Map<String, Object> map:list){
System.out.println(map.get("NAME"));
}
}
}
结果:
***排序前***
朱元璋
常遇春
张无忌
郭靖
洪七公
***排序后***
常遇春
郭靖
洪七公
张无忌
朱元璋
作者:itmyhome