不使用比较器手动排序bean列表

时间:2015-08-31 15:28:21

标签: java

public class Organization {

    protected List<Address> addresses;
    protected String SourceId;
    protected String organizationId;
    protected String organizationName;
}
public class ReferenceOrg{
public List<Organization> getAllOrgs() {
        List<Organization> listOfOrgsTemp = new ArrayList<Organization>();
        List<Organization> listOfOrgs = new ArrayList<Organization>();
        listOfOrgsTemp.addAll(webToolWS.getAllProviders());
        listOfOrgsTemp.addAll(webToolWS.getAllVendors());
        for(Organization org : listOfOrgsTemp) {
            listOfOrgs.add(org);
        }
        return listOfOrgs;
    }
}

我想按组织名对listOfOrgs进行排序,但是我无法在我的组织类上实现比较器,它被不同的项目使用,并且他们想要对不同的字段进行排序。如果没有修改组织类,我如何手动对listofOrgs列表进行排序。enter code here

1 个答案:

答案 0 :(得分:0)

我刚学会了如何使用Comparator用逗号分隔数字字符串数据JTable。我没有尝试执行我的代码添加(并且必须删除一些引用以获得编译)但是这可能会帮助您开始。标记为// *******或由public class ReferenceOrg { static Comparator compareOrgs; // *********************** public List<Organization> getAllOrgs() { // ************************************************************ compareOrgs = (Comparator) new Comparator() { @Override public int compare(Object oo1, Object oo2) { Organization or1 = (Organization)oo1; Organization or2 = (Organization)oo2; String o1 = or1.organizationId; String o2 = or2.organizationId; return o1.compareTo(o2); } }; // ************************************************************ List<Organization> listOfOrgsTemp = new ArrayList<Organization>(); List<Organization> listOfOrgs = new ArrayList<Organization>(); ... for(Organization org : listOfOrgsTemp) { listOfOrgs.add(org); } Collections.sort(listOfOrgs, compareOrgs); // ******************* return listOfOrgs; } 包围的行显示要添加的代码。

java.util.Collections 
public static <T> void sort(List<T> list, Comparator<? super T> c) 
Sorts the specified list according to the order induced by the specified comparator. 
All elements in the list must be mutually comparable using the specified comparator
 (that is, c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the list). 
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort. 
The specified list must be modifiable, but need not be resizable. 
Implementation Note: 
This implementation defers to the List.sort(Comparator) method using the specified list and comparator. 
Parameters: 
list - the list to be sorted.
c - the comparator to determine the order of the list. A null value indicates that the elements' 
natural ordering should be used. 

来自Javadoc:

{{1}}