繁体   English   中英

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

[英]Group and then sort a list using java comparator

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

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

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

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

        return lTransactionDate2.compareTo(lTransactionDate1);
    }

提前致谢。

取决于您的比较器。 如果先比较产品说明,然后再比较日期,我想您应该得到的是什么,即首先按说明对产品项进行排序,然后按日期对具有相同说明的项进行排序。

这是一个多字段排序的例子。这里的实现是先按纬度,经度再按高度进行排序。

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

}

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

Bean 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一次完成两种排序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM