首页 > 技术文章 > java对集合中时间进行排序

ghc520 2019-09-25 09:50 原文

 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     }

 

推荐阅读