zoukankan      html  css  js  c++  java
  • 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("
    ");
            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  +"
    ";
        }
    }

    定义比较规则:

    /**
     * 按照价格的降序排列
     */
       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
               ]
    
        }
  • 相关阅读:
    Python批量 png转ico
    线性回归
    【论文集合】多语言机器翻译
    【论文集合】curriculum learning总结/课程学习论文
    crf++分词
    强化学习的探索策略方式
    关于multiprocessing中的logging的数据打印到本地失败或重复问题
    置信区间绘图、以10次平均值为例
    打印CSDN博客内容JS
    SUMO学习笔记(3)
  • 原文地址:https://www.cnblogs.com/111testing/p/9158140.html
Copyright © 2011-2022 走看看