<< MAP SET LIST 的不同 | 首页 | 如何在Linux/Unix运行一个守护Java程序 >>

自己编写实现java.util.Comparator自定义排序规则

import java.util.Comparator;

import java.util.Iterator;

import java.util.List;

import java.util.LinkedList;

/**

* 多列组合排序器

*

Title:

*

*

Description:

*

*

Copyright: Copyright (c) 2005

*

*

Company:

*

* @author not attributable

* @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;

}

}

//多列排序;按镇,终端

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);

标签 :



发表评论 发送引用通报