实现java.util.Comparator接口,对对象集合进行多属性组合排序

时间:2022-08-02 02:51:01

Commons - BeanUtils 提供了很多功能,其中一个很有用的是对对象集合进行排序,如Collections.sort(peoples, new BeanComparator("age"));

另外,可以使用java.util.Collections的sort方法可以对collection集合进行排序,包括多列组合排序,下面是自己实现java.util.Comparator,定制对象属性排序规则的例子:

package com.lph.test;

import java.util.Comparator;

import java.util.Iterator;

import java.util.List;

import java.util.LinkedList;

/** 

* 自定义对象多属性(多列)组合排序
* <p>Title: is a Class</p> 

* <p>Description: 类</p> 

* <p>Copyright: Copyright (c) 2006</p> 

* <p>Company: sunrise</p> 

@author islph 
@version 1.0 
*/ 
public class CompositeComparator implements Comparator {

    /** in the condition list, comparators' priority decrease from head to tail */

    private List comparators = new LinkedList();

    /** get the comparators, you can manipulate it as need. */

    public List getComparators() {

        return comparators;

    }

    /** add a batch of comparators to the condition list */

    public void addComparators(Comparator[] comparatorArray) {

        if (comparatorArray == null) {

            return;

        }

        for (int i = 0; i < comparatorArray.length; i++) {

            comparators.add(comparatorArray[i]);

        }

    }

    /** compare by the priority */

    public int compare(Object o1, Object o2) {

        for (Iterator iterator = comparators.iterator(); iterator.hasNext();) {

            Comparator comparator = (Comparator) iterator.next();

            int result = comparator.compare(o1, o2);

            if (result != 0) {

                return result;

            }

        }

        return 0;

    }

}

 

// 多列排序;按属性COUNTY_NO镇,DDP_ID终端 组合排序

CompositeComparator myComparator = new CompositeComparator();

myComparator.addComparators(

new Comparator[] {

new Comparator() {

    public int compare(Object a, Object b) {

        DisplayForm aObj, bObj;

        aObj = (DisplayForm) a;

        bObj = (DisplayForm) b;

        String aStr = (String) aObj.get("COUNTY_NO");

        String bStr = (String) bObj.get("COUNTY_NO");

        return aStr.compareTo(bStr);

    }

}

new Comparator() {

    public int compare(Object a, Object b) {

        DisplayForm aObj, bObj;

        aObj = (DisplayForm) a;

        bObj = (DisplayForm) b;

        String aStr = (String) aObj.get("DDP_ID");

        String bStr = (String) bObj.get("DDP_ID");

        return aStr.compareTo(bStr);

    }

}

});

java.util.Collections.sort(listResult, myComparator);