zoukankan      html  css  js  c++  java
  • JAVA 按时间排序

    排序使用的是

    Collections.sort(List,Comparator)

    自定义类实现Comparator接口

    假如A的值大于B,你返回1。这样调用Collections.sort()方法就是升序

    假如A的值大于B,你返回-1。这样调用Collections.sort()方法就是降序

    import com.lanhetech.api.iso8583msg.utils.MyLog;
    import com.lanhetech.model.user.Trade;
    
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Comparator;
    import java.util.Date;
    
    /**
     * 订单按时间排序,最近的日期显示在上面
     */
    public class ComparatorDate implements Comparator {
        public static final String TAG = "ComparatorDate";
    
    
        SimpleDateFormat format = new SimpleDateFormat("yyyy/M/d H:mm:ss");
    
        public int compare(Object obj1, Object obj2) {
            Trade t1 = (Trade) obj1;
            Trade t2 = (Trade) obj2;
         //   return t1.getTradetime().compareTo(t2.getTradetime());  // 时间格式不好,不然可以直接这样比较
            Date d1, d2;
            try {
                d1 = format.parse(t1.getTradetime());
                d2 = format.parse(t2.getTradetime());
            } catch (ParseException e) {
                // 解析出错,则不进行排序
                MyLog.e(TAG, "ComparatorDate--compare--SimpleDateFormat.parse--error");
                return 0;
            }
            if (d1.before(d2)) {
                return 1;
            } else {
                return -1;
            }
        }
    }

    使用:

     ComparatorDate c = new ComparatorDate();
     Collections.sort(notRechargeTrades, c);  // 订单按时间排序
     Collections.sort(isFinishTrades, c);
     private List<Trade> notRechargeTrades = new ArrayList<>();
     private List<Trade> backMoneyTrades = new ArrayList<>();
     private List<Trade> isFinishTrades = new ArrayList<>();
    public class Trade extends ComUser implements Serializable {
        ....
        private String tradetime;        // 充值时间
        ....


  • 相关阅读:
    在python3.7下怎么安装matplotlib与numpy
    kNN(从文本文件中解析数据)
    k-近邻算法(kNN)笔记
    第二章--k-近邻算法(kNN)
    C++学习笔记一 —— 两个类文件互相引用的处理情况
    (转) C++中基类和派生类之间的同名函数的重载问题
    初试 Matlab 之去除水印
    (转) linux之sort用法
    vim 简单配置
    hdu 5358 First One
  • 原文地址:https://www.cnblogs.com/H-BolinBlog/p/6022021.html
Copyright © 2011-2022 走看看