对列表进行排序<String>基于日期 - Java

问题描述 投票:0回答:1

我正在尝试根据日期对列表进行排序。

名单:

[数据重播/上游/20230911/2023-09-11/WIRE_ISSN.WIRE_CRTD_0057c620ea6040849da9bceb977e7332-2023-09-11-19-30-10-00445.txt,数据重播/上游/20230911/2023- 09-11/WIRE_ISSN.WIRE_CRTD_00e1cd4e425243bda8e09ee2b7b2334f- 2023-09-11-19-30-02-00554.txt,数据重播/上游/20230911/2023-09-11/WIRE_ISSN.WIRE_CRTD_021b63466ff6406d8b30b25bda63b49f-2023-09-11-19-30-21-002 18.txt,数据重播/上游/20230911/2023-09-11/WIRE_ISSN.WIRE_CRTD_049a681a00214155b7dab7c94c871341-2023-09-11-19-30-15-00036.txt,datareplay/upstream/20230911/2023-09-11/W IRE_ISSN.WIRE_CRTD_068e490f3b78453293e84bdfb49112ad-2023-09- 11-19-30-14-00288.txt,数据重播/上游/20230911/2023-09-11/WIRE_ISSN.WIRE_CRTD_0694fca541d0486689c6591b16cb1fbc-2023-09-11-19-30-14-00405.txt,数据重播/上游/20230911/ 2023-09-11/WIRE_ISSN.WIRE_CRTD_0a8d4975741e4b088ead2bfd1edee1ad-2023-09-11-19-30-07-00188.txt]

我想要排序的部分是 - 2023-09-11-19-30-10-00445

任何指导我做的帮助都非常感谢。

java arrays list sorting
1个回答
0
投票

在 Java 中,您可以使用自定义

Comparator
根据每个文本的指定部分对字符串列表进行排序。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;

public class Main {
    public static void main(String[] args) {
        String[] fileArray = {
            "datareplay/upstream/20230911/2023-09-11/WIRE_ISSN.WIRE_CRTD_0057c620ea6040849da9bceb977e7332-2023-09-11-19-30-10-00445.txt",
            "datareplay/upstream/20230911/2023-09-11/WIRE_ISSN.WIRE_CRTD_00e1cd4e425243bda8e09ee2b7b2334f-2023-09-11-19-30-02-00554.txt",
            // Add more entries
        };

        Arrays.sort(fileArray, new CustomComparator());

        for (String filePath : fileArray) {
            System.out.println(filePath);
        }
    }

    static class CustomComparator implements Comparator<String> {
        @Override
        public int compare(String str1, String str2) {
            String[] tokens1 = str1.split("-");
            String[] tokens2 = str2.split("-");

            String dateStr1 = tokens1[tokens1.length - 7];
            String dateStr2 = tokens2[tokens2.length - 7];

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSSSS");

            try {
                long date1 = dateFormat.parse(dateStr1).getTime();
                long date2 = dateFormat.parse(dateStr2).getTime();

                return Long.compare(date1, date2);
            } catch (ParseException e) {
                e.printStackTrace();
                return 0;
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.