2014-01-25 36 views
2

我有一個項目列表,每個項目都有一個價格字段。有些商品的價格等於999.排序時,我希望價格== 999的元素始終位於列表的底部,無論排序方向是升序還是降序。如何在排序時忽略某個值,以便始終顯示在排序列表的底部

我已經厭倦了下面的代碼,它適用於排序從低到高(升序),但不是降序時。

Collections.sort(itemList, new Comparator<Item>() { 
    @Override 
    public int compare(Item o1, Item o2) { 
     if(sort == 4){ // Low to High 
      return Double.compare(o1.getPrice(), o2.getPrice()); 
     }else{ // High to Low 
      return Double.compare(o2.getPrice(), o1.getPrice()); 

     } 
    } 
}); 
+0

另一種方法是之前從列表中刪除了'999'項目排序並將其放回列表中。 – assylias

回答

5

按升序排列:

Collections.sort(items, new Comparator<Item>() 
{ 
    @Override 
    public int compare(Item o1, Item o2) 
    { 
     if (o1.getPrice() == 999 && o1.getPrice() < o2.getPrice()) { 
      return 1; 
     } 
     if (o2.getPrice() == 999) { 
      return -1; 
     } 
     return Double.compare(o1.getPrice(), o2.getPrice()); 
    } 
}); 

而對於降序排列:

Collections.sort(items, Collections.reverseOrder(new Comparator<Item>() 
{ 
    @Override 
    public int compare(Item o1, Item o2) 
    { 
     if (o1.getPrice() == 999 || o2.getPrice() == 999) { 
      return 1; 
     } 
     return Double.compare(o1.getPrice(), o2.getPrice()); 
    } 
})); 

測試:

List<Item> items = new ArrayList<Item>(); 
items.add(new Item(10)); 
items.add(new Item(50)); 
items.add(new Item(1050)); 
items.add(new Item(999)); 
items.add(new Item(40)); 
items.add(new Item(999)); 
items.add(new Item(30)); 
items.add(new Item(1050)); 

輸出:

升序

10.0 
30.0 
40.0 
50.0 
1050.0 
1050.0 
999.0 
999.0 

降序

1050.0 
1050.0 
50.0 
40.0 
30.0 
10.0 
999.0 
999.0 
0

重寫你compare()識別999爲被視爲大於一個特殊情況(如果排序低到高)或小於(如果排序高到低)的任何其他值。

0

您可以使用此比較:

Collections.sort(itemList, new Comparator<Item>() { 
    @Override 
    public int compare(Item o1, Item o2) { 

     if (o1.getPrice() == 999) 
      return -1; 
     else if (o2.getPrice() == 999) 
      return 1; 

     if (sort == 4) { // Low to High 
      return Double.compare(o1.getPrice(), o2.getPrice()); 
     } else { // High to Low 
      return Double.compare(o2.getPrice(), o1.getPrice()); 
     } 
    } 
}); 
相關問題