在流中查找值,而不是最大值的几倍

我想查找第一个日期早于实际最大日期的一年。我尝试使用流来执行此操作,但是我被卡住了。


List<String> intervalIdList = new HashSet();


intervalIdList.add("2018-01");

intervalIdList.add("2017-12");

intervalIdList.add("2017-11");

intervalIdList.add("2017-10");

...

intervalIdList.add("2016-12"); // this is the value I want to find


LocalDate localDateSet =

                    intervalIdSet.stream()

                            .map(s-> LocalDate.parse(s))

                            .sorted()

                            .filter(localDate -> localDate < max(localDate)) // something like max(localDate)

                            .findFirst();

我是否必须将最大过滤值写入流外部的变量?



忽然笑
浏览 143回答 2
2回答

凤凰求蛊

似乎您正在寻找今天前一年的日期上限:List<String> intervalIdList = new ArrayList<>();intervalIdList.add("2018-01-01");intervalIdList.add("2017-12-01");intervalIdList.add("2017-11-01");intervalIdList.add("2017-10-01");intervalIdList.add("2016-12-01"); // this is the value I want to findLocalDate localDateSet = intervalIdList.stream()&nbsp; &nbsp; &nbsp; &nbsp; .map(LocalDate::parse)&nbsp; &nbsp; &nbsp; &nbsp; .filter(ld -> ld.isBefore(LocalDate.now().minus(Period.of(1, 0, 0))))&nbsp; &nbsp; &nbsp; &nbsp; .max(Comparator.comparingLong(LocalDate::toEpochDay))&nbsp; &nbsp; &nbsp; &nbsp; .get();System.out.println(localDateSet);那打印 2016-12-01请注意,我必须在日期字符串中添加天数,以匹配期望的默认格式LocalDate.parse。由于使用了过滤器,因此显式检查可选变量以处理没有值与谓词匹配的情况可能更安全:Optional<LocalDate> max = intervalIdList.stream()&nbsp; &nbsp; &nbsp; &nbsp; .map(LocalDate::parse)&nbsp; &nbsp; &nbsp; &nbsp; .filter(ld -> ld.isBefore(LocalDate.now().minus(Period.of(1, 0, 0))))&nbsp; &nbsp; &nbsp; &nbsp; .max(Comparator.comparingLong(LocalDate::toEpochDay));并在读取最大值之前进行检查:if(max.isPresent()) {&nbsp; &nbsp; LocalDate ld = max.get();}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java