根据从字符串

时间:2016-03-10 20:25:04

标签: java android arrays sorting

我有一个Array List(Type String),它看起来像:

  [2015-03-2, 2015-12-2, 2017-02-1, 2015-10-7, 2018-04-1, 2016-01-2, 2015-08-1, 2016-04-2, 2016-05-1, 2016-02-12, 2016-03-6]

我想按降序排序,例如:

[2018-04-1, 2017-02-1,2016-05-1,2016-03-6,2015-03-2......]

我不知道怎么做,因为它不是日期类型(项目是字符串)我不能使用Collections.sort(myArray)任何想法或提示我将如何做到这一点?它对我很有帮助,谢谢

更新:我知道我需要的是:

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd h:m");
System.out.println(sdf.parse(startDate).before(sdf.parse(endDate)));

但我不知道从哪里开始

3 个答案:

答案 0 :(得分:3)

希望这可以解决:

("John", "Car 1, Car 2, Car 3")
("Kate", "Car 2, Car 4, Car 5")

上面的代码使用Collections API,其中Collections.sort(myArray,new Comparator<String>(){ private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); @Override public int compare(String s1, String s2){ return sdf.parse(s1).compareTo(sdf.parse(s2)); } }); 是由Java实现的方法。 Collections.sort类中有两种排序方法。首先是对Collections元素列表进行排序。另一个将基于Comparable对任何List进行排序,允许用户编写特定逻辑来比较特定Type的2个元素。因此,我们需要实现的只是Comparator来完成我们的工作。

答案 1 :(得分:2)

您可以使用sort函数:

PingTruck.Main(args);
Console.WriteLine(PingTruck.PingStatus);
Console.ReadLine();

答案 2 :(得分:1)

public class Main {
    public static void main(String[] args) {
        String[] list = new String[]  {"2015-03-2", "2015-12-2", "2017-02-1", "2015-10-7", "2018-04-1", "2016-01-2", "2015-08-1", "2016-04-2", "2016-05-1", "2016-02-12", "2016-03-6"};

        Arrays.asList(list).stream().map(s -> LocalDate.parse(s, DateTimeFormatter.ofPattern("yyyy-MM-d"))).sorted().forEach(System.out::println);
    }
}

结果

2015-03-02
2015-08-01
2015-10-07
2015-12-02
2016-01-02
2016-02-12
2016-03-06
2016-04-02
2016-05-01
2017-02-01
2018-04-01