java - 比较列表中字符串的日期

标签 java sorting date-parsing date-comparison

我在继续操作时遇到问题。我有一个列表,每个位置都包含一个字符串(在短语中末尾有一个日期)

示例:

I am new here 20/8/2019 

我想这样对列表进行排序: 在位置零,我想要包含最旧日期的短语,而以下位置的日期将更近。

我尝试使用 SimpleDateFormat 和 Date,但我不知道该怎么做。

String variable, variable2, c;
int d = 0;
for(int i = 0; i < lista.size(); i++) {
    for(int j = 1; j <lista.size(); j++) {
        variable = lista.get(i);
        variable2 = lista.get(j);
        c = compareDates(variable, variable2);
        lista.add(d,c);
        d++;
    }
}

private static Date compareDates(String variable, String variable2) throws ParseException {
    SimpleDateFormat formateador = new SimpleDateFormat("dd/MM/yyyy");
    String var = formateador.format(variable);
    String var2 = formateador.format(variable2);
    if (var.before(var2)) {
        return var;
    } else {
        if (var2.before(var1)) {

        } else {

        }
        return null;
    }
}

线程“main”java.lang.Error中出现异常: Unresolved 编译问题: 类型不匹配:无法从日期转换为字符串

at Ejercicio.ClaseMain.leerDes(ClaseMain.java:124)

Line 124: c = compareDates(variable, variable2);

视觉示例:列表中的每个位置都有一个带有日期的短语:

enter image description here

问题是,我读了一个 .txt 文件,其中有几行。 文件内容:

Sevilla reserves himself to Apoel and wins without brilliance; sport Julen Lopetegui revolutionized the eleven with the aim of giving rest to the regulars, which did not prevent his team from adding his second triumph of the competition sportyou 10/10/2019

A painting by Banksy of the British Parliament occupied by chimpanzees, sold >for 11 million euros culture An oil of artist Banksy representing the British House of Commons full of chimpanzees was topped on Thursday at an auction in London for 9.8 million pounds (11 million euros) 10/2019

我用了一段时间来读取文件行并将每一行保存在列表中的每个位置,并且我想对列表进行排序。旧日期 ---> 最近日期。

最佳答案

考虑到List中的所有字符串都具有相同的格式,并且在分割后的第四个索引处具有date,如下所示

List<String> list = new ArrayList<>();
list.add("I am new here 20/11/2019 ");
list.add("I am Deadpool here 20/7/2019 ");
list.add("I am IronMan here 20/6/2019 ");

现在使用比较器根据LocalDateList进行排序

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/M/yyyy");
list.sort(Comparator.comparing(str->LocalDate.parse(str.split(" ")[4],formatter)));

    System.out.println(list);  //I am IronMan here 20/6/2019 , I am Deadpool here 20/7/2019 , I am new here 20/11/2019 ]

关于java - 比较列表中字符串的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58779289/

相关文章:

java - SimpleDateFormat 没有正确解析日期

java - 如何在android中设备方向改变后保持listview项目的高亮

c# - 以各种格式呈现时解析日期的推荐方法

java - HibernateTemplate 可以和 EntityManager 共存吗?

sorting - Redis - 寻求数据建模建议

Pandas GroupBy 和 sort_values 无法按预期工作

scala - Scala排序是否稳定?

Java 8 DateTimeFormatter 解析可选部分

java - 重复实例化匿名类是否浪费?

java - Neo4J 和 Spring 返回空关系