简体   繁体   English

在JAVA中按日期和数字排序2D字符串数组?

[英]Sorting 2D String Array by date and number in JAVA?

I have a String[][] array with following data. 我有一个包含以下数据的String[][]数组。 I want to sort this array 我想对这个数组进行排序

  1. according to the integer value in column data[][1] , 根据列data[][1]的整数值,
  2. according to the date in column data[][2] . 根据列data[][2]的日期。 Output should be 2D String array. 输出应为2D字符串数组。
 String[][] data = { {"text", "5", "Fri, 04 Feb 2011 13:17:31 GMT"}, {"text", "5", "Fri, 04 Feb 2011 14:24:47 GMT"}, {"text", "8", "Fri, 05 Sep 2014 20:43:57 GMT"}, {"text", "4", "Fri, 08 Nov 2013 16:35:34 GMT"}, {"text", "4", "Fri, 15 Aug 2014 10:00:16 GMT"}, {"text", "4", "Fri, 16 May 2014 15:03:08 GMT"}, {"text", "6", "Fri, 31 Jan 2014 13:12:06 GMT"}, {"text", "4", "Mon, 04 Aug 2014 09:14:36 GMT"}, {"text", "4", "Mon, 08 Sep 2014 03:55:54 GMT"}, {"text", "1", "Mon, 08 Sep 2014 12:53:09 GMT"} }; 

Just Wrap the Array into a list using Arrays.asList . 只需使用Arrays.asList将数组包装到列表中Arrays.asList

http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList%28T...%29 http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList%28T...%29

Now use Collections.sort and create a custom Comparator that reads the data from the arrays inside the list and sorts accordingly. 现在使用Collections.sort并创建一个自定义的Comparator ,该Comparator从列表内的数组中读取数据并进行相应的排序。

http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort%28java.util.List,%20java.util.Comparator%29 http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort%28java.util.List,%20java.util.Comparator%29

First compare on the integer, if the integers are the same then parse the string into a Date and compare the two Date objects. 首先比较整数,如果整数相同,则将字符串解析为Date并比较两个Date对象。

I hope sorting the integer won't be a issue to you i will show you how you can sort according to date 希望对整数进行排序不会对您造成问题,我将向您展示如何根据日期进行排序

Arrays.sort(data, new Comparator<String[]>() { // sort the array
    SimpleDateFormat f = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
    // SimpleDateFormat  to parse the String Date
    @Override
    public int compare(String[] o1, String[] o2) {
        try {
            return f.parse(o1[2]).compareTo(f.parse(o2[2]));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return -1;
    }
});
for(int i = 0; i < data.length; i++){ // display the result
    for(int j = 0; j < data[i].length; j++)
    {
        System.out.print(data[i][j]);
        if(j < data[i].length - 1) System.out.print(" ");
    }
    System.out.println();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM