繁体   English   中英

使用流从 Java 中的 csv-File 中按日期和时间排序

[英]Sorting by date and time from csv-File in Java using streams

我正在尝试按日期和时间对我的 csv 文件进行排序。有没有可能用流来做到这一点? csv 文件中的日期格式如下所示。 26.01.2020 23:14:25。 先感谢您。

public class Logfilereader {
    public static void main(String[] args) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY hh:mm:ss");


        Stream<String> rows1 = Files.lines(Path.of("C:\\Users\\julit\\IdeaProjects\\Logfilereader\\src\\testdata1.csv"));
        rows1
                .map(x -> x.split(";"))
                .filter(x -> x.length == 5)
                .filter(x -> Integer.parseInt(x[1])>=0)
                .filter(x -> x[2].equals("HYGRO")||x[2].equals("TEMP"))
                .filter(x -> x[4].equals("CELSIUS")||x[4].equals("PERCENT"))
                .forEach(x -> System.out.println(x[0]+ " "+x[1]+" " +x[2]+ " "+x[3]+ " "+ x[4]));

        rows1.close();


        }



    }

tl;博士

.sorted(
        Comparator.comparing( ( String line ) -> 
            LocalDateTime.parse( 
                line.split( "," )[ 1 ] ,  // Grab date-time portion of line.
                DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss" ) 
            ) 
        )
)

细节

在传递Comparator实现时调用Stream#sorted

对于每一行,我们的比较器调用String#split来获取由两部分组成的数组,名称和日期时间。 我们使用[1]的从零开始的索引提取该数组的第二个元素。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss" );
String input =
        """
        Alice,23/01/2022 23:30:00
        Bob,12/01/2022 12:30:00
        Carol,15/01/2022 15:30:00
        Davis,01/01/2022 01:30:00
        """;

List < String > result =
        input.lines()
                .sorted(
                        Comparator.comparing( ( String line ) -> LocalDateTime.parse( line.split( "," )[ 1 ] , f ) )
                )
                .toList();

跑的时候。

结果 = [戴维斯,01/01/2022 01:30:00,鲍勃,12/01/2022 12:30:00,卡罗尔,15/01/2022 15:30:00,爱丽丝,23/01/2022 23 :30:00]

提示:向数据发布者提供有关ISO 8601标准的教育。 ISO 8601 定义了用于交换日期时间值的文本格式。 该标准旨在消除歧义,并促进机器和人类的阅读。 java.time类默认使用这些标准格式,无需指定格式模式。

暂无
暂无

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

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