项目中经常需要用到比如地区列表按照中文的拼音首字母排序,但是有时候获取到的地区列表是对象的形式,有地区id,地区名称两个属性。这里主要涉及到两个技术点:
1、对象按属性排序;2、中文按拼音首字母排序。下面给出自己整理好的demo:- import java.text.Collator;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
-
- import org.apache.commons.beanutils.BeanComparator;
- import org.apache.commons.collections.ComparatorUtils;
- import org.apache.commons.collections.comparators.ComparableComparator;
- import org.apache.commons.collections.comparators.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(1,"3","五"));
- list.add(new CompareTipA(2,"1","六"));
- list.add(new CompareTipA(5,"5","二"));
- list.add(new CompareTipA(3,"4","四"));
- list.add(new CompareTipA(8,"4","四"));
- list.add(new CompareTipA(4,"2","一"));
-
- Comparator mycmp = ComparableComparator.getInstance();
- mycmp = ComparatorUtils.nullLowComparator(mycmp); //允许null
- mycmp = ComparatorUtils.reversedComparator(mycmp); //逆序
-
- ArrayList<Object> sortFields = new ArrayList<Object>();
- Comparator<Object> comparator=Collator.getInstance(java.util.Locale.CHINA);
-
- sortFields.add(new BeanComparator("name",comparator)); //name正序 (主)
- sortFields.add(new BeanComparator("id", mycmp)); //id逆序 (副)
- ComparatorChain multiSort = new ComparatorChain(sortFields);
- Collections.sort(list,multiSort);
-
- for (int i =0;i<list.size();i++) {
- System.out.println(list.get(i)); //输出
- /* [id=5,name=二,age=5]
- [id=2,name=六,age=1]
- [id=8,name=四,age=4]
- [id=3,name=四,age=4]
- [id=1,name=五,age=3]
- [id=4,name=一,age=2]*/
- }
- }
-
- 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 compareTo(Object o) {
- // return this.comparator.compare(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;
- }
- }
复制代码 注意:需要导入的三个包:commons-beanutils-1.8.3.jar commons-collections-3.2.1.jar commons-logging-1.1.3.jar
commons-collections包不能用官网上的4.0版本,因为从源码中可以看见commons-beanutils包调用的就是commons-collections3.2版本的api,4.0的没兼容;commons-logging包也是commons-beanutils包所需要的。 |
|