java實現Comparable接口和Comparator接口,並重寫compareTo方法和compare方法


原文地址https://segmentfault.com/a/1190000005738975

 

實體類:java.lang.Comparable(接口) + comareTo(重寫方法),業務排序類 java.util.Comparator(接口) + compare(重寫方法).

這兩個接口我們非常的熟悉,但是 在用的時候會有一些不知道怎么下手的感覺,現在用案例進行總結,消除對這個知識點的理解盲區(個人的理解,如果有錯誤 請多多指教)。
一,在實際的需求中,我們需要根據對象的各種屬性(標題,時間,點擊率,銷售額...)進行排序(升序,降序),可以在數據庫的sql上進行處理,但是 不是每一個場景 都適合在sql上進行處理,我們有時候需要在程序根據不同的屬性,對一個對象進行各種排序 通過頁面呈現給用戶。
下面有這樣的一個需求,一種商品(商品名,銷售量,生產日期),根據生產日期降序 銷售量升序 商品名稱降序

思路:首先按照日期降序,如果日期相同 按照銷售量升序,如果銷售量相同,按周商品的名稱降序
1,創建需要比較的對象的java bean
創建 Bean的快捷鍵:
1),帶參數的構造器:// Shift + Alt + S -->O
2),不帶參數的構造器: //Alt + / 生成空的構造方法
3),生成 get set方法:// Shift + Alt + S --> R + Table + Enter + Shift +Table -->Enter

/**
 * 商品po類
 */
public class Items implements java.lang.Comparable<Items> {
    private String title;
    private int hits;
    private Date pubTime;
    public Items() {}
    public Items(String title, int hits, Date pubTime) {
        super();
        this.title = title;
        this.hits = hits;
        this.pubTime = pubTime;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public int getHits() {
        return hits;
    }
    public void setHits(int hits) {
        this.hits = hits;
    }
    public Date getPubTime() {
        return pubTime;
    }
    public void setPubTime(Date pubTime) {
        this.pubTime = pubTime;
    }
    //時間降序 點擊量升序 標題降序
    @Override
    public int compareTo(Items o) {
        int result = 0;
        //按照生產時間降序
        result = - this.pubTime.compareTo(o.pubTime);
        if(0==result){//如果生產時間相同 就按照銷售量升序排列
            result = this.hits-o.hits;
            if(0==result){//如果銷售量相同 按照名字降序排列
                result = - this.title.compareTo(o.title);
            }
        }
        return result;
    }
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("商品名稱").append(this.title);
        sb.append("銷售量").append(this.hits);
        sb.append("生產時間").append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(this.pubTime)).append("\n");
        return sb.toString();
    }
  }

 

2,造數據,比較

    //時間降序, 銷售量升序, 標題降序
public static void main(String[] args) {
      List<Items> item 
              = new ArrayList<Items>();
      item.add(new Items("abcitems"
              ,30,new Date(System.currentTimeMillis()-1000*60*60)));
      item.add(new Items("abcfgitems"
               ,30,new Date(System.currentTimeMillis()-1000*60*50)));
      item.add(new Items("abcditems"
               ,100,new Date()));
      item.add(new Items("abefNews"
              ,50,new Date(System.currentTimeMillis()-1000*60*60)));
      System.out.println("----------排序前----------");
      System.out.println(item);
      System.out.println("----------排序后----------");
      Collections.sort(item);
      System.out.println(item);
}

 

二,Comparator的應用場景
一般比較字符串是按照unicode的大小進行排序的,但是我需要按照字符串的長度進行排序,下面是實現的案例:
首先,定義比較的業務規則

/**
 * 定義業務的比較規則,我需要按照字符串的長度進行比較(在實際的場景中,可以根據業務的需求,靈活的改變比較規則,實現排序)
 */
public class CompareString implements java.util.Comparator<String> {
    @Override
    public int compare(String o1, String o2) {
        int len1 = o1.length();
        int len2 = o2.length();
        return -(len1-len2);//需要按照降序排列
    }
}

 

比較 字符串的長度,按照 降序排列

    public static void main(String[] args) {
        List<String>  list 
                = new ArrayList<String>();
       list.add("abc");
       list.add("abcd");
       list.add("ab");
       list.add("abd");
       Collections.sort(list,new CompareString());
       System.out.println(list);
     //[abcd, abc, abd, ab]
    }

 

比如 商品,我需要按照價格的降序排列,代碼如下:
商品 po類

/**
 * 商品po類
 */
public class Products {
    private String title;
    private int price;
    public Products() {}
    public Products(String title, int price) {
        super();
        this.title = title;
        this.price = price;
    }
    
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }
    @Override
    public String toString() {
        return "title=" + title+",price=" + price  +"\n";
    }
}

 

定義比較規則:

/**
 * 按照價格的降序排列
 */
   public class ProductCompare implements java.util.Comparator<Products> {
    @Override
     public int compare(Products o1, Products o2) {
         return -( o1.getPrice()-o2.getPrice()>0?1: (o1.getPrice()==o2.getPrice()?0:-1));
    }
  }

 

數據比較:

 
public static void main(String[] args) {
        List<Products> product 
             = new ArrayList<Products>();
        product.add(new Products("a",120));
        product.add(new Products("b",143432));
        product.add(new Products("c",1892));
        product.add(new Products("d",11092));
        Collections.sort(product,new ProductCompare());
        System.out.println(product);
      結果:
           [title=b,price=143432
            title=d,price=11092
             title=c,price=1892
             title=a,price=120
           ]

    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM