目前项目中一个head(object)会包含多个Dtl明细(object),需要依赖Dtl其中的几个属性进行排序。
TreeMap使用了key,而key不能重复,这样就不能处理相同key的dtl明细数据。
于是我查了下API ,发现可以使用 Colletions.sort实现该功能。需要实现Comparator接口。定义比较的规则。 如下事例:
[@more@]目前项目中一个head会包含多个Dtl明细,需要依赖Dtl其中的几个属性进行排序。
使用TreeMap如下:
TreeMap myTree = new TreeMap(); Iterator itr = nkeiTranHd.getDtlIterator(); while (itr.hasNext()) { nkeiTrnDtl = (NkeiTranDtl) itr.next(); myTree.put(nkeiTrnDtl.getKijoSyhnCd().getHnbn(), nkeiTrnDtl); } Iterator hnbn = myTree.keySet().iterator(); while (hnbn.hasNext()) { nkeiTrnDtl = (NkeiTranDtl) myTree.get(hnbn.next()); |
但TreeMap使用了key,而key不能重复,这样就不能处理相同key的dtl明细数据。
于是我查了下API
发现可以使用 Colletions.sort实现该功能。需要实现Comparator接口。定义比较的规则。
如下事例:
这样即使dtl中的属性是相同的也不会影响排序。
package jp.co.isetan.rb.regsykai.syukei.oltp;
import java.util.*;
/**
* Test
*
* @version $Revision:$ $Date:$
*/
public class Test {
- public Test() {
super();
// TODO Auto-generated constructor stub
}
static class ItemComparator implements Comparator {
public int compare(Object element1, Object element2) {
TestBean item1 = (TestBean) element1;
TestBean item2 = (TestBean) element2;
return item1.getId().compareTo(item2.getId());
}
}
class TestBean {
String id;
String name;
public void setId(String newVal) {
id = newVal;
}
public String getId() {
return id;
}
public void setName(String newVal) {
name = newVal;
}
public String getName() {
return name;
}
}
public void testTreeMap() {
TestBean tb1 = new TestBean();
tb1.setId("2");
tb1.setName("2");
TestBean tb2 = new TestBean();
tb2.setId("3");
tb2.setName("3");
TestBean tb3 = new TestBean();
tb3.setId("2");
tb3.setName("2");
TestBean tb4 = new TestBean();
tb4.setId("1");
tb4.setName("1");
List tm= new ArrayList();
tm.add(tb1);
tm.add(tb2);
tm.add(tb3);
tm.add(tb4);
Collections.sort(tm, new ItemComparator());
Iterator it = tm.iterator();
while (it.hasNext()) {
TestBean tt = (TestBean)it.next();
System.out.println(tt.getId());
}
/* for (int i=0; i
System.out.println(((TestBean)tm.get(i)).getId());
}*/
}
public static void main(String[] args) {
Test t = new Test();
t.testTreeMap();
}
}
public static void main(String[] args) {
Test t = new Test();
t.testTreeMap();
}
}
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/118026/viewspace-802769/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/118026/viewspace-802769/