Java中对象按照属性排序
项目中经常需要用到比如地区列表按照中文的拼音首字母排序 但是有时候获取到的地区列表是对象的形式 有地区id 地区名称两个属性 这里主要涉及到两个技术点
对象按属性排序 中文按拼音首字母排序 下面给出自己整理好的demo:
import java text Collator;
import java util ArrayList;
import java util Collections;
import java util Comparator;
import mons beanutils BeanComparator;
import llections ComparatorUtils;
import parators ComparableComparator;
import parators ComparatorChain;
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>()
list add(new CompareTipA( 五 ))
list add(new CompareTipA( 六 ))
list add(new CompareTipA( 二 ))
list add(new CompareTipA( 四 ))
list add(new CompareTipA( 四 ))
list add(new CompareTipA( 一 ))
Comparator mycmp = ComparableComparator getInstance()
mycmp = ComparatorUtils nullLowComparator(mycmp)
//允许null
mycmp = ComparatorUtils reversedComparator(mycmp) //逆序
ArrayList<Object> sortFields = new ArrayList<Object>()
Comparator<Object> parator=Collator getInstance(java util Locale CHINA)
sortFields add(new BeanComparator( name parator)) //name正序 (主)
sortFields add(new BeanComparator( id mycmp))
//id逆序 (副)
ComparatorChain multiSort = new ComparatorChain(sortFields)
Collections sort(list multiSort)
for (int i = ;i<list size() i++) {
System out println(list get(i))
//输出 /*
[id= name=二 age= ]
[id= name=六 age= ]
[id= name=四 age= ]
[id= name=四 age= ]
[id= name=五 age= ]
[id= name=一 age= ]*/
}
}
public CompareTipA(int id String age String name) {
this id = id;
this name = name;
this age = age;
}
public int getId() {
return this id;
}
public void setId(int id) {
this id = id;
}
public String getName() {
return this name;
}
public void setName(String name) {
this name = name;
}
//
public int pareTo(Object o) { //
return pare(this o) // }
public String toString() {
return [id= + this id + name= + this name + age= + this age + ] ;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this age = age;
} }
注意 需要导入的三个包 mons beanutils jar
mons collections jar
mons logging jar
lishixinzhi/Article/program/Java/hx/201311/25790