一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - java 實現Comparable接口排序,升序、降序、倒敘

java 實現Comparable接口排序,升序、降序、倒敘

2020-08-19 17:28256g的胃 Java教程

這篇文章主要介紹了java 實現Comparable接口排序,升序、降序、倒敘,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

本人由于項目開發中需要對查詢結果list進行排序,這里根據的是每一個對象中的創建時間降序排序。本人講解不深,只實現目的,如需理解原理還需查閱更深的資料。

1.實現的效果

java 實現Comparable接口排序,升序、降序、倒敘

2.創建排序的對象

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.practice.test.comparable;
import java.util.Date;
 
/**
 * 描述:要比較的對象
 *
 * @author cui
 * @create 2018-12-18 14:07
 */
public class MySortBean implements Comparable<MySortBean> {
  private String name;
  private int age;
  private Date createTime;
 
 
  public String getName() {
    return name;
  }
 
  public void setName(String name) {
    this.name = name;
  }
 
  public int getAge() {
    return age;
  }
 
  public void setAge(int age) {
    this.age = age;
  }
 
  public Date getCreateTime() {
    return createTime;
  }
 
  public void setCreateTime(Date createTime) {
    this.createTime = createTime;
  }
 
//  @Override
//  public int compareTo(MySortBean o) {
//    if (this.age>o.age){
//      return -1;
//    }else if (this.age==o.age){
//      return 0;
//    }
//    return 1;
//  }
    @Override
    public int compareTo(MySortBean o) {
      if (this.createTime.compareTo(o.getCreateTime())>0){
        return -1;
      }else if (this.createTime.compareTo(o.getCreateTime())==0){
        return 0;
      }
      return 1;
    }
 
  @Override
  public String toString() {
    return "MySortBean{" +
        "name='" + name + '\'' +
        ", age=" + age +
        '}';
  }
}

3.編寫test方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.practice.test;
import com.practice.test.comparable.MySortBean;
import com.spring.testlist.util.DateUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
/**
 * 描述:
 * 測試比較器
 *
 * @author cui
 * @create 2018-12-18 14:10
 */
@RunWith(SpringJUnit4ClassRunner.class)
public class TestCompare {
 
  @Test
  public void testComparable(){
    MySortBean m1 = new MySortBean();
    m1.setAge(1);
    m1.setCreateTime(DateUtil.parseDate("2019-01-21 16:13:18"));
    MySortBean m2 = new MySortBean();
    m2.setAge(2);
    m2.setCreateTime(DateUtil.parseDate("2019-01-23 16:13:18"));
    MySortBean m3 = new MySortBean();
    m3.setAge(3);
    m3.setCreateTime(DateUtil.parseDate("2019-01-22 16:13:18"));
    MySortBean m4 = new MySortBean();
    m4.setAge(4);
    m4.setCreateTime(DateUtil.parseDate("2019-01-24 16:13:18"));
    MySortBean m5 = new MySortBean();
    m5.setAge(5);
    m5.setCreateTime(DateUtil.parseDate("2019-01-25 16:13:18"));
    List<MySortBean> l = new ArrayList<>(5);
    l.add(m1);
    l.add(m2);
    l.add(m4);
    l.add(m5);
    l.add(m3);
 
    System.out.println("排序前:");
    for (MySortBean i:l) {
      System.out.println(DateUtil.formatDate(i.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
    }
    /**
     * 自定義排序
     * 直接return -1 倒敘排列,list順序顛倒輸出
     *
     * if (o1.getAge()>o2.getAge()){
     *           return 1;
     *         }
     *         return -1;
     *         以上升序輸出
     *
     * if (o1.getAge()>o2.getAge()){
     *           return -1;
     *         }
     *         return 1;
     *         以上降序輸出
     *
     *
     */
/*    Comparator<MySortBean> comparator = new Comparator<MySortBean>() {
      @Override
      public int compare(MySortBean o1,MySortBean o2) {
        if (o1.getAge()>o2.getAge()){
          return -1;
        }
        return 1;
      }
    };
    l.sort(comparator);*/
    l.sort(MySortBean::compareTo);
    System.out.println("--------");
    System.out.println("排序后:");
    for (MySortBean i:l) {
      System.out.println(DateUtil.formatDate(i.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
    }
  }
}

4.時間格式化工具類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package com.spring.testlist.util;
import org.apache.commons.lang3.time.DateFormatUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
 
/**
 * 日期工具類, 繼承org.apache.commons.lang.time.DateUtils類
 *
 * @author cui
 * @create 2018-10-26 15:30
 **/
public class DateUtil extends org.apache.commons.lang3.time.DateUtils{
 
    private static String[] parsePatterns = {
        "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
        "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
        "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
 
    /**
     * 得到當前日期字符串 格式(yyyy-MM-dd)
     */
    public static String getDate() {
      return getDate("yyyy-MM-dd");
    }
  /**
   * 得到當前日期字符串 格式(yyyyMMdd)
   */
  public static String getSizeDate() {
    return getDate("yyyyMMdd");
  }
 
    /**
     * 得到當前日期字符串 格式(yyyy-MM-dd) pattern可以為:"yyyy-MM-dd" "HH:mm:ss" "E"
     */
    public static String getDate(String pattern) {
      return DateFormatUtils.format(new Date(), pattern);
    }
 
    /**
     * 得到日期字符串 默認格式(yyyy-MM-dd) pattern可以為:"yyyy-MM-dd" "HH:mm:ss" "E"
     */
    public static String formatDate(Date date, Object... pattern) {
      if (date == null) {
        return null;
      }
      String formatDate = null;
      if (pattern != null && pattern.length > 0) {
        formatDate = DateFormatUtils.format(date, pattern[0].toString());
      } else {
        formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
      }
      return formatDate;
    }
 
    /**
     * 得到日期時間字符串,轉換格式(yyyy-MM-dd HH:mm:ss)
     */
    public static String formatDateTime(Date date) {
      return formatDate(date, "yyyy-MM-dd HH:mm:ss");
    }
 
    /**
     * 得到當前時間字符串 格式(HH:mm:ss)
     */
    public static String getTime() {
      return formatDate(new Date(), "HH:mm:ss");
    }
 
    /**
     * 得到當前日期和時間字符串 格式(yyyy-MM-dd HH:mm:ss)
     */
    public static String getDateTime() {
      return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
    }
 
    /**
     * 得到當前年份字符串 格式(yyyy)
     */
    public static String getYear() {
      return formatDate(new Date(), "yyyy");
    }
 
    /**
     * 得到當前月份字符串 格式(MM)
     */
    public static String getMonth() {
      return formatDate(new Date(), "MM");
    }
 
    /**
     * 得到當天字符串 格式(dd)
     */
    public static String getDay() {
      return formatDate(new Date(), "dd");
    }
 
    /**
     * 得到當前星期字符串 格式(E)星期幾
     */
    public static String getWeek() {
      return formatDate(new Date(), "E");
    }
 
    /**
     * 日期型字符串轉化為日期 格式
     * { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
     * "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm",
     * "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
     */
    public static Date parseDate(Object str) {
      if (str == null) {
        return null;
      }
      try {
        return parseDate(str.toString(), parsePatterns);
      } catch (ParseException e) {
        return null;
      }
    }
    /**
     * 獲取過去的天數
     *
     * @param date
     * @return
     */
    public static long pastDays(Date date) {
 
      long t = System.currentTimeMillis()- date.getTime();
      return t / (24 * 60 * 60 * 1000);
    }
    /**
     * 獲取過去的小時
     *
     * @param date
     * @return
     */
    public static long pastHour(Date date) {
      long t =System.currentTimeMillis() - date.getTime();
      return t / (60 * 60 * 1000);
    }
    /**
     * 獲取過去的分鐘
     *
     * @param date
     * @return
     */
    public static long pastMinutes(Date date) {
      long t = System.currentTimeMillis() - date.getTime();
      return t / (60 * 1000);
    }
    /**
     * 轉換為時間(天,時:分:秒.毫秒)
     *
     * @param timeMillis
     * @return
     */
    public static String formatDateTime(long timeMillis) {
      long day = timeMillis / (24 * 60 * 60 * 1000);
      long hour = (timeMillis / (60 * 60 * 1000) - day * 24);
      long min = ((timeMillis / (60 * 1000)) - day * 24 * 60 - hour * 60);
      long s = (timeMillis / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
      long sss = (timeMillis - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000 - min * 60 * 1000 - s * 1000);
      return (day > 0 ? day + "," : "") + hour + ":" + min + ":" + s + "." + sss;
    }
    /**
     * 獲取兩個日期之間的天數
     *
     * @param before
     * @param after
     * @return
     */
    public static double getDistanceOfTwoDate(Date before, Date after) {
      long beforeTime = before.getTime();
      long afterTime = after.getTime();
      return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
    }
    public static String getFirstDayOfMonth() {
      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
      //獲取當前月第一天:
      Calendar c = Calendar.getInstance();
      c.add(Calendar.MONTH, 0);
      c.set(Calendar.DAY_OF_MONTH, 1);//設置為1號,當前日期既為本月第一天
      String first = format.format(c.getTime());
      return first;
    }
    /**
     * @param args
     * @throws ParseException
     */
    public static void main(String[] args) throws ParseException {
// System.out.println(formatDate(parseDate("2010/3/6")));
// System.out.println(getDate("yyyy年MM月dd日 E"));
// long time = new Date().getTime()-parseDate("2012-11-19").getTime();
// System.out.println(time/(24*60*60*1000));
      String sizeDate = formatDate(new Date(),"yyyyMMdd");
      System.out.println(sizeDate);
    }
}

到此就結束了,具體的要實現什么排序,根據示例自己腦補擴展就好了,例子中備注也已經標注。

在使用排序注意兩個坑

1.要排序的字段為空的異常處理

2.要排序的字段相等的異常處理

補充知識:Java中的自然排序和比較器排序

寫在前面的話:剛開始學習著兩者排序時我也是一頭霧水,雖然能寫出來但是稀里糊涂,幾時該用哪個排序一點想法都沒有,后來經過研究這兩者的作用點不同,自然排序作用在實體類上,而比較器排序作用在裝實體類的集合上。

1、自然排序:java.lang.Comparable

Comparable 接口中只提供了一個方法: compareTo(Object obj) ,該方法的返回值是 int 。如果返回值為正數,則表示當前對象(調用該方法的對象)比 obj 對象“大”;反之“小”;如果為零的話,則表示兩對象相等。

總結為一句話:實現Comparable,重寫 compareTo方法

案列:以TreeMap為例,默認的升序,可以重寫自然排序的方法改變原有排序

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public static void testComparable(){
    TreeMap<Car,Object> tmp = new TreeMap<Car,Object>();
    tmp.put(new Car(4), "肆");
    tmp.put(new Car(1), "壹");
    tmp.put(new Car(5), "伍");
    tmp.put(new Car(3), "三");
    tmp.put(new Car(2), "貳");
    System.out.println(tmp);
    //結果://{Car [price=5.0]=伍, Car [price=4.0]=肆, Car [price=3.0]=三, Car [price=2.0]=貳, Car [price=1.0]=壹}
  }
//自定義TreeMap排序方法  自然排序 
 
class Car implements Comparable<Car>{
  private double price;
  
  public double getPrice() {
    return price;
  }
 
  public void setPrice(double price) {
    this.price = price;
  }
 
  public Car(int price) {
    super();
    this.price = price;
  }
 
  @Override
  public int compareTo(Car o) {
    // TODO Auto-generated method stub
    if(this.price>o.getPrice()){
      return -1;//大的往前排
    }else if(this.price<o.getPrice()){
      return 1;//小的往后排
    }else{
      return 0;
    }
  }
 
  @Override
  public String toString() {
    return "Car [price=" + price + "]";
  }

2、比較器排序:java.util.Comparator

總結為一句話:實現Comparator 接口,重寫compare方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public static void testComparator(){
    //HashMap<Integer,Object> hm = new HashMap<Integer,Object>();
    TreeMap<Integer,Object> tmp = new TreeMap<Integer,Object>(new MyComparatorBigtoSmall());
    tmp.put(4, "肆");
    tmp.put(1, "壹");
    tmp.put(5, "伍");
    tmp.put(3, "三");
    tmp.put(2, "貳");
    //System.out.println(tmp);//默認排序結果:{1=壹, 2=貳, 3=三, 4=肆, 5=伍}
    System.out.println(tmp);//修改為比較器排序(升序){5=伍, 4=肆, 3=三, 2=貳, 1=壹}
  }
 
//自定義TreeMap排序方法  比較器排序 
  class MyComparatorBigtoSmall implements Comparator<Integer>{
 
    @Override
    public int compare(Integer o1, Integer o2) {
      // TODO Auto-generated method stub
      return o2-o1;
    }
  }

以上這篇java 實現Comparable接口排序,升序、降序、倒敘就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。

原文鏈接:https://blog.csdn.net/C1041067258/article/details/86578188

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 精品国产日韩一区三区 | 亚洲男人的天堂网 | 果冻传媒在线完整免费观 | 色老板最新网站视频地址 | 调教全程肉动画片在线观看 | 久久综合中文字幕佐佐木希 | 美女被躁了在线观看视频 | 大象传媒免费网址 | 校园全黄h全肉细节文 | 五月天综合久久 | 91次元成年破解版 | 精品9e精品视频在线观看 | 114毛片免费观看网站 | 国产成年人视频 | 91国内精品久久久久影院优播 | 婷婷天天 | 免费人成黄页在线观看69 | 美琪美腿白丝交小说 | 亚洲国产欧美在线成人aaaa | 久久久久影视 | 狠狠干快播 | 亚洲欧美久久婷婷爱综合一区天堂 | 深夜免费看 | 91香蕉视频导航 | 99久久免费精品视频 | 粗暴hd另类另类 | 国产成人性毛片aaww | 99精品国产成人一区二区在线 | 国产亚洲精品激情一区二区三区 | 美女被吸乳老师羞羞漫画 | 免费看麻豆视频 | 精品午夜久久网成年网 | 教室里老师好紧h | 无限在线看免费视频大全 | 国产精品久久久久久爽爽爽 | 欧美国产高清 | 欧美日韩国产亚洲一区二区 | 国产精品亚洲一区二区 | 摸咪网在线影院在线观看 | 国产爽视频 | 停停色|