JAVA中使用靜態內部類Comparator實現集合的排序
阿新 • • 發佈:2018-12-26
比起Comparable介面比較器Comparator為我們在排序中提供了更寬鬆和更加廣泛的應用例項:在實際中,常常需要對一個商品按照不同屬性來排序,這時我們就能通過寫出自己的Comparator來實現不同的排序方式
public class Goods{ private int goodsId; //編號 private String goodsName; //品名 private double goodsOriginalPrice; //原價 private double goodsSellPrice; //賣價 private int goodsInStock; //庫存 private ArrayList<String> goodsShowPics; //展示圖集合url private ArrayList<String> goodsDetailPics; //商品圖集合url private String goodsProducer; //生產者 private String goodsProducePlace; //產地 private Timestamp goodsInDate; //入庫時間 private String goodsPackage; //包裝內容 private String goodsCM; //產品規格 private String goodsService; //售後服務 private int goodsViewed; //商品瀏覽量 private int goodsSold; //商品銷售量 private double goodsPoint; //商品評分 public Goods(){ } }
這時如果在類Goods中插入靜態內部final Comparator類就可以實現
使用靜態內部final類好處在於呼叫時候結構清晰,呼叫方便,並且無需重複例項化比較器物件,節省了系統開支
在Goods類中插入如下程式碼:
實現了Goods類的多種比較器之後,就可以在程式中呼叫Collections.sort(arg1,arg2)方法了/** * 靜態內部類比較按入庫時間 //降序 */ public static final Comparator<Goods> GOODS_BY_INDATE = new Comparator<Goods>(){ public int compare(Goods o1, Goods o2) { return o2.getGoodsInDate().compareTo(o1.getGoodsInDate()); } }; /** * 靜態內部類比較按售價 */ public static final Comparator<Goods> GOODS_BY_SELLPRICE = new Comparator<Goods>() { public int compare(Goods o1, Goods o2) { return (int) (o1.getGoodsSellPrice()-o2.getGoodsSellPrice()); } }; /** * 靜態內部類比較按售價 //降序 */ public static final Comparator<Goods> GOODS_BY_SELLPRICE_DESC = new Comparator<Goods>() { public int compare(Goods o1, Goods o2) { return (int) (o2.getGoodsSellPrice()-o1.getGoodsSellPrice()); } }; /** * 靜態內部類比較按點選量 //降序 */ public static final Comparator<Goods> GOODS_BY_GOODSVIEWD = new Comparator<Goods>() { public int compare(Goods o1, Goods o2) { // TODO Auto-generated method stub return o2.getGoodsViewed()-o1.getGoodsViewed(); } }; /** * 靜態內部類按銷量排序 //降序 */ public static final Comparator<Goods> GOODS_BY_GOODSSOLD = new Comparator<Goods>() { public int compare(Goods o1, Goods o2) { return o2.getGoodsSold()-o1.getGoodsSold(); } }; /** * 靜態內部類按評分排序 //降序 */ public static final Comparator<Goods> GOODS_BY_POINT = new Comparator<Goods>() { public int compare(Goods o1, Goods o2) { return (int) (o2.getGoodsPoint()-o1.getGoodsPoint()); } };
例如,對於已經存在的名為showResult的Goods集合用下面的程式碼就可以實現排序了:
當然,不使用內部類也是可以的,用到Comparator類,你就可以輕鬆的按照各種喜歡的方式排序了if(sortType.equals("bySold")){ //按銷量時候 Collections.sort(showResult, Goods.GOODS_BY_GOODSSOLD); } if(sortType.equals("byViewed")){ //按點選量時候 Collections.sort(showResult, Goods.GOODS_BY_GOODSVIEWD); } if(sortType.equals("byInDate")){ //按入庫時間時候 Collections.sort(showResult, Goods.GOODS_BY_INDATE); } if(sortType.equals("byPoint")){ //按評分時候 Collections.sort(showResult, Goods.GOODS_BY_POINT); } if(sortType.equals("byPrice")){ //按價格時候 Collections.sort(showResult, Goods.GOODS_BY_SELLPRICE); } if(sortType.equals("byPriceDown")){ //按價格降序時候 Collections.sort(showResult, Goods.GOODS_BY_SELLPRICE_DESC); }