0

假设我有一个 bean 集合,它在为其编写的自定义比较器的帮助下按 empld、dept、project 排序,并使用 apache 集合 ComparatorChain 对该 bean 的列表进行排序。豆子如下。

public class Employee  {

    protected String empId; //alphanumeric e.g.abc123
    protected String empFullName;   
    protected String empAddress;
    protected String dept;
    protected String project;
    protected String customer;

    public String getEmpId() {
        return empId;
    }
    public void setEmpId(String empId) {
        this.empId = empId;
    }
    public String getEmpFullName() {
        return empFullName;
    }
    public void setEmpFullName(String empFullName) {
        this.empFullName = empFullName;
    }
    public String getEmpAddress() {
        return empAddress;
    }
    public void setEmpAddress(String empAddress) {
        this.empAddress = empAddress;
    }
    public String getDept() {
        return dept;
    }
    public void setDept(String dept) {
        this.dept = dept;
    }
    public String getProject() {
        return project;
    }
    public void setProject(String project) {
        this.project = project;
    }

    public String getCustomer() {
        return customer;
    }
    public void setCustomer(String customer) {
        this.customer = customer;
    }


}

客户价值可以是,比如说:公司、政府、大学

现在假设集合中有数千条记录(bean),现在我想要的是相同的 empId(可以出现两次),如果客户是公司,则将其移动到具有客户名称 University 的相同 empId 之下。客户的记录可能不按顺序排列,所以任何一个都可以先出现,等等。

所以基本上我想移动两个或多个具有相同empId的记录并且其中一个有customer =Company将其移动到具有相同empId的订单下方,例如

自定义排序

我怎样才能以一种有效且可能的线程安全的方式实现这种记录的交换/重新排列。

4

2 回答 2

0

如果要对集合中的记录进行排序,则需要使该对象类实现比较器并根据需要实现方法。

于 2012-09-09T18:29:38.770 回答
0

我解决了这个问题如下:

  1. 您可以创建一个单独的比较器类,该类实现了 Comparator 并具有公司、政府、大学的比较方法。

  2. 您可以在公司、政府、大学的 Employee 类中创建创建者比较器方法,如下所示:

    公共静态比较器 COMPARE_BY_COMPANY = new Comparator() { public int compare(Employee o1, Employee o2) {

            if (o1.company == null && o2.company == null) return 0;   
    
            if (o1.company != null && o2.company == null) return -1;
            if (o1.company == null && o2.company != null) return 1;
    
            return o1.company.compareTo (o2.company);    
        }
    };
    

虽然第一种方法更好,但第二种方法也没有害处。

然后在您想要自定义排序顺序的类中,执行以下操作:

 ComparatorChain chain = new ComparatorChain();
             chain.addComparator(Employee.COMPARE_BY_COMPANY);
             chain.addComparator(Employee.COMPARE_BY_GOVERNMENT);
             chain.addComparator(Employee.COMPARE_BY_UNIVERSITY);


             Collections.sort(EmployeeList, chain);

其中 ComparatorChain 是 org.apache.commons.collections.comparators.ComparatorChain。

上面的代码将按公司排序,然后按政府排序,然后按大学排序,最后对列表进行排序,结果将按该顺序显示。

于 2013-03-28T03:24:35.627 回答