方式一
不支持含有重复字段进行排序
/**
* sqlite不支持中文排序,改用java排序
* 根据指定的对象属性字段,排序对象集合,顺序
* @param list
* @param field
* @return
*/
public static List sortListByField(List<?> list,String field){
List temp = new ArrayList();
try{
List<String> fields = new ArrayList<String>();
for(Object obj:list){
fields.add(getFieldValueByName(field,obj).toString());
}
Collections.sort(fields,Collator.getInstance(java.util.Locale.CHINA));
for(String name:fields){
for(Object o:list){
if(name.equals(getFieldValueByName(field,o).toString())){
temp.add(o);
}
}
}
}catch(Exception ex){
ex.printStackTrace();
}
return temp;
}
/**
* 根据属性名获取属性值
* @param fieldName
* @param o
* @return
*/
private static Object getFieldValueByName(String fieldName, Object o) {
try {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + (fieldName.substring(1));
Method method = o.getClass().getMethod(getter, new Class[] {});
Object value = method.invoke(o, new Object[] {});
return value;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取属性名数组
* @param o
* @return
*/
private String[] getFiledName(Object o) {
Field[] fields = o.getClass().getDeclaredFields();
String[] fieldNames = new String[fields.length];
for (int i = 0; i < fields.length; i++) {
System.out.println(fields[i].getType());
fieldNames[i] = (fields[i].getName());
}
return fieldNames;
}
参考:http://blog.csdn.net/linshutao/article/details/7693625
方式二
支持含有重复字段进行排序
/**
* sqlite不支持中文排序,改用java排序
* 根据指定的对象属性字段,排序对象集合,顺序
* @param list
* @param field
* @return
*/
public static List sortListByField(List<?> list,String field){
List temp = new ArrayList();
try{
List<String> fields = new ArrayList<String>();
int len = list.size();
for(int i=0;i<len;i++){
Object obj = list.get(i);
fields.add(getFieldValueByName(field,obj).toString()+"@"+i);
}
Collections.sort(fields,Collator.getInstance(java.util.Locale.CHINA));
for(String name:fields){
String location = name.substring(name.lastIndexOf("@")+1);
int index = Integer.parseInt(location);
temp.add(list.get(index));
}
}catch(Exception ex){
ex.printStackTrace();
}
return temp;
}