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

问题描述:

我有一个包含产品项目和购买时间的列表。是否可以使用比较java来首先根据产品描述对此列表进行排序,然后按购买日期对它进行排序?组然后使用java比较器对列表进行排序

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

这是我到目前为止,排序日期罚款。

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

     return lTransactionDate2.compareTo(lTransactionDate1); 
    } 

在此先感谢。

+2

[最好的方法来比较对象的多个字段?](http://*.com/questions/369512/best-way-to-compare-objects-by-multiple-fields) – dogbane 2011-03-07 11:20:09

+0

umm所以创建另一个比较对象似乎是要走的路?或将使用枚举工作呢?枚举方法看起来更好 – user648036 2011-03-07 11:24:20

取决于您的比较器。如果首先比较产品描述和日期,我认为你应该得到你以后的内容,即产品项目首先按照描述排序,然后具有相同描述的项目按日期排序。

+0

嗯,我不知道你的意思。 java比较方法是否通过列表一次?或多次?我不想比较产品说明并按顺序排列,然后再按日期进行比较排序,因为这会“破坏”以前订购的产品说明排序。 – user648036 2011-03-07 11:26:40

+0

@ user648036这不是Peter建议你做的。但是,由于您已将主题引入,因此可以先按日期排序整个列表,然后再按产品说明排序,这样就可以得到您需要的结果,因为'Collections.sort()'中的排序算法是保守的。当然你不应该这样做,但很高兴知道你可以。 – biziclop 2011-03-07 11:39:48

+0

@ user648036,我的意思是说,通过实施和使用正确的比较器,您可以根据您的意愿一次性订购列表。在此期间@Emil添加了示例代码,虽然具有不同的属性,但是 - 说明了这个想法。 – 2011-03-07 12:33:54

这是一个用多个字段进行排序的例子。这里的实现是根据纬度,经度和高度进行排序。

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

} 

我希望这将有助于你如何与多个字段排序,以得到一个想法,然后works.You可以根据自己的需要写一个比较。

+0

谢谢队友。我会放弃这一点 – user648036 2011-03-07 11:35:43

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在一次传做这两类。