使用java比较器对列表进行分组然后排序

时间:2011-03-07 11:15:35

标签: java

我有一个包含产品项目的清单以及何时购买。是否可以使用比较器java首先按产品说明对此列表进行排序,然后按购买日期对其进行排序?

到目前为止,我可以使用它按日期或描述或其他字段的顺序对列表进行排序,但我想知道是否可以使用多个字段对其进行排序?

这就是我到目前为止对日期进行排序的好处。

public int compare(Transaction aTransaction1, Transaction aTransaction2)
    {
        Date lTransactionDate1 = aTransaction1.getTransactionDate();
        Date lTransactionDate2 = aTransaction2.getTransactionDate();

        return lTransactionDate2.compareTo(lTransactionDate1);
    }

提前致谢。

3 个答案:

答案 0 :(得分:0)

取决于您的比较器。如果它首先比较产品描述,然后是日期,我认为你应该得到你想要的东西,即产品项目首先按描述排序,然后具有相同描述的项目按日期排序。

答案 1 :(得分:0)

以下是使用多个字段进行排序的示例。这里的实现是根据纬度,经度然后按高度进行排序。

public class LatLongHt implements Comparable<LatLongHt> {
    public double lat,lng,ht;
    public LatLongHt(double latitude, double longitude, double ht2) {
        this.lat=latitude;
        lng=longitude;
        ht=ht2;
    }
    @Override
    public int compareTo(LatLongHt obj) {
        int result;
        if((result=compareValue(this.lat,obj.lat))==0)      
            if((result=compareValue(this.lng, obj.lng))==0) 
                result=compareValue(this.ht, obj.ht);
        return result;
    }
    private int compareValue(double val1, double val2) {
        if(val1==val2)
            return 0;
        if(val1>val2)
            return 1;       
        return -1;
    }

    @Override
    public String toString(){
        return "("+lat+','+lng+','+ht+')';

    }


    @ Override
    public boolean equals(Object o){
        if(!(o instanceof LatLongHt))       
            return false;
        LatLongHt that=(LatLongHt)o;
        return that.lat==this.lat && that.lng==this.lng && that.ht==this.ht;
    }

  @Override
  public int hashCode() {
     int result=11;  
     result=(int)(31*result+Double.doubleToLongBits(lat));
     result=(int)(31*result+Double.doubleToLongBits(lng));
     result=(int)(31*result+Double.doubleToLongBits(ht));
    return result;
}

}

我希望这可以帮助您了解如何使用多个字段进行排序。然后您可以根据需要编写比较器。

答案 2 :(得分:0)

Bean Comparator允许您对类中的字段进行排序,以便为描述和日期创建单独的比较器。然后,您可以使用Group Comparator将比较器合并为一个。您的代码如下:

BeanComparator description = new BeanComparator(Transaction.class, "getDescription");
BeanComparator date = new BeanComparator(Transaction.class, "getTransactionDate");
GroupComparator gc = new GroupComparator(description, date);
Collections.sort(yourList, gc);

或者您可以使用手动创建的各个自定义比较器,只需使用GroupComparator一次完成两种排序。