gpt4 book ai didi

java - Lambda Java 8 - 如何在将字符串列表流式传输到日期列表时进行转换

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:07:04 26 4
gpt4 key购买 nike

有没有办法将字符串列表(在流式传输和收集时)也转换为新的日期列表?

我的尝试:

我定义了一个 SimpleDateFormat 并尝试在下面的代码中使用它,但我无法让它一起工作。

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.mm.yyyy");

ArrayList<Date> dateList = stringList.stream()
.filter(s -> s.startsWith("<"))
.collect(Collectors.toList());

解决方案

根据使用 map 的提示,我现在得到了一个看起来像这样的可行解决方案。当然欢迎对此进行任何优化!

int year = 2016;
int month = 2;
int day = 15;


final List<LocalDate> dateListEarlier = dateList.stream()
.filter(s -> s.startsWith("<"))
.map(s -> s.substring(1).trim())
.map(s -> LocalDate.parse(s, formatter))
.sorted()
.filter(d -> d.isAfter(LocalDate.of(year, month, day)))
.collect(Collectors.toList());

最佳答案

由于您使用的是 Java8,因此您可以利用新的 DateTime API

    List<String> dateStrings = Arrays.asList("12.10.2016", "13.10.2016", "14.10.2016");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
List<LocalDate> localDates = dateStrings.stream().map(date -> LocalDate.parse(date, formatter)).collect(Collectors.toList());
System.out.println(localDates);

输出

[2016-10-12, 2016-10-13, 2016-10-14]

关于java - Lambda Java 8 - 如何在将字符串列表流式传输到日期列表时进行转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40047313/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com