java對集合中時間進行排序


 1 Collections.sort(list, new Comparator<String>() {
 2     DateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 3     @Override
 4     public int compare(String o1, String o2) {
 5         try {
 6                return f.parse(o1).compareTo(f.parse(o2));
 7         } catch (ParseException e) {
 8                throw new IllegalArgumentException(e);
 9         }
10     }
11 });

在Collections.sort(list, new Comparator<String>()  中的list只需要將時間的集合放入。時間的格式可自定義。

現在的是對時間進行正序排序,如果要倒序則將return中的o1和02交換位置。

項目中完成實例:

 1 public static String disposeFrequencePath(String path) {
 2         String[] str = path.split(",");
 3         //定義兩個集合,一個是帶時間類型,一個不帶
 4         ArrayList<String> list = new ArrayList<String>();
 5         ArrayList<String> list1 = new ArrayList<String>();
 6         for (int i = 0; i < str.length; i++) {
 7             String one = str[i].split("#")[0];
 8             String two = str[i].split("#")[1];
 9             if(two.equals("1")) {
10                 one = yesToday+" "+one;
11             }else if(two.equals("2")){
12                 one = temToday+" "+one;
13             }else {
14                 one = Today+" "+one;
15             }
16             list.add(one);
17             list1.add(one+"#"+two);
18         }
19         //對不帶時間類型的集合進行排序
20         Collections.sort(list, new Comparator<String>() {
21             DateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
22             @Override
23             public int compare(String o1, String o2) {
24                 try {
25                     return f.parse(o1).compareTo(f.parse(o2));
26                 } catch (ParseException e) {
27                     throw new IllegalArgumentException(e);
28                 }
29             }
30         });
31         String now = "";
32         //用已經排序好的時間對帶時間類型的進行對比,獲取排序好並且帶時間類型
33         for (int i = 0; i < list.size(); i++) {
34             String aa = list.get(i);
35             String jj = "";
36             for (int j = 0; j < list1.size(); j++) {
37                 String fir = list1.get(j).split("#")[0];
38                 if(aa.equals(fir)) {
39                     jj = list1.get(j).split("#")[1];
40                     break;
41                 }
42             }
43             now += aa.split(" ")[1]+"#"+jj+",";
44         }
45         return now;
46     }

 


免責聲明!

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



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