项目中经常需要用到比如地区列表按照中文的拼音首字母排序但是有时候获取到的地区列表是对象的形式有地区id地区名称两个属性这里主要涉及到两个技术点
对象按属性排序中文按拼音首字母排序下面给出自己整理好的demo:
import javatextCollator;
import javautilArrayList;
import javautilCollections;
import javautilComparator;
import monsbeanutilsBeanComparator;
import llectionsComparatorUtils;
import paratorsComparableComparator;
import paratorsComparatorChain;
public class CompareTipA {
private int id;
private String name;
private String age;
@SuppressWarnings(unchecked)
public static void main(String []args) {
ArrayList<Object> list = new ArrayList<Object>()
listadd(new CompareTipA(五))
listadd(new CompareTipA(六))
listadd(new CompareTipA(二))
listadd(new CompareTipA(四))
listadd(new CompareTipA(四))
listadd(new CompareTipA(一))
Comparator mycmp = ComparableComparatorgetInstance()
mycmp = ComparatorUtilsnullLowComparator(mycmp)
//允许null
mycmp = ComparatorUtilsreversedComparator(mycmp) //逆序
ArrayList<Object> sortFields = new ArrayList<Object>()
Comparator<Object> comparator=CollatorgetInstance(javautilLocaleCHINA)
sortFieldsadd(new BeanComparator(namecomparator)) //name正序 (主)
sortFieldsadd(new BeanComparator(id mycmp))
//id逆序 (副)
ComparatorChain multiSort = new ComparatorChain(sortFields)
Collectionssort(listmultiSort)
for (int i =;i<listsize()i++) {
Systemoutprintln(listget(i))
//输出 /*
[id=name=二age=]
[id=name=六age=]
[id=name=四age=]
[id=name=四age=]
[id=name=五age=]
[id=name=一age=]*/
}
}
public CompareTipA(int id String ageString name) {
thisid = id;
thisname = name;
thisage = age;
}
public int getId() {
return thisid;
}
public void setId(int id) {
thisid = id;
}
public String getName() {
return thisname;
}
public void setName(String name) {
thisname = name;
}
//
public int compareTo(Object o) { //
return pare(this o) // }
public String toString() {
return [id= + thisid + name= + thisname +age= + thisage +];
}
public String getAge() {
return age;
}
public void setAge(String age) {
thisage = age;
} }
注意需要导入的三个包commonsbeanutilsjar
commonscollectionsjar
commonsloggingjar
commonscollections包不能用官网上的版本因为从源码中可以看见commonsbeanutils包调用的就是commonscollections版本的api的没兼容commonslogging包也是commonsbeanutils包所需要的