【问题标题】:sort an ArrayList<String> according to dates parsed from the String根据从字符串中解析的日期对 ArrayList<String> 进行排序
【发布时间】:2016-06-25 21:23:18
【问题描述】:

我有一个数组列表(字符串类型),它看起来像:

  [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)));

但我不知道从哪里开始

【问题讨论】:

  • 使用流将字符串转换为日期,然后排序
  • 流? Stream API ??

标签: java android arrays sorting


【解决方案1】:

希望一切顺利:

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));
    }

});

以上代码使用集合 API,其中Collections.sort 是由 Java 实现的方法。 Collections 类中有 2 种排序方法。首先是对Comparable 元素的列表进行排序。另一个将根据Comparator 对任何列表进行排序,这允许用户编写特定逻辑来比较特定类型的两个元素。因此,我们只需要实现Comparator 即可完成我们的工作。

【讨论】:

  • 为什么要声明 sdf 静态?
  • 这样它就不可能有多个副本
  • 值得注意的是:根据输入数组的大小以及Strings最终是否会转换为Dates,将整个在进行排序之前将数组添加到 Dates... 这样您就不会为每次比较创建两个新对象
  • @MozenRath 嘿,兄弟,我是个菜鸟,我用你的代码对我的数组进行排序,但你能告诉我如何才能得到结果吗?结果我的意思是排序数组??
  • 在答案中添加了详细描述
【解决方案2】:

您可以使用排序功能:

Collections.sort(myArray, new Comparator<String>(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

public int compare(String a, String b){
   //Parse it into date and compare thr long values
   return sdf.parse(a).compareTo(sdf.parse(b))
}
});

【讨论】:

  • compare 应该能识别出相等的项。
  • 为每个调用创建日期格式以进行比较会产生开销
  • 只是一个例子。也可以使用 compareTo 函数。
  • 我的意思是告诉你如何实现它。
【解决方案3】:
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

【讨论】:

  • android 不支持流
  • 那么@MozenRath 答案是你最好的解决方案
猜你喜欢
  • 2015-03-31
  • 2014-05-13
  • 2012-02-24
  • 2020-01-03
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
相关资源
最近更新 更多