For example, if you want to advance the date by 5 days from a certain starting date ( startYmd
) and find the date when the timing exceeds Today.
LocalDate ymd; //Starting date
while (ymd.isBefore(LocalDate.now())) {
ymd = ymd.plusDays(5);
}
System.out.println(ymd); //The first day after Today, which is 5 days from the starting date
I write.
Somehow, I recently thought that I shouldn't write `while statement`
, so I decided to write it with `StreamAPI`
.
Oh, it's Java 8 after knowing that Java 9 has `Stream # takeWhile`
.
So, this code was created.
LocalDate startYmd; //Starting date
Stream.iterate(startYmd, ymd -> ymd.plusDays(5))
.filter(ymd -> !ymd.isBefore(LocalDate.now()))
// .sorted()← With this, an infinite loop! !!
.findFirst()
.ifPresent(ymd -> {
System.out.println(ymd); //The first day after Today, which is 5 days from the starting date
});
It's been a long time since I received the comment, but I've fixed it.
It seems that the stateful intermediate operation `sort ()`
was the cause of the infinite loop, and at that time there was a great deal of lack of study ...
(By the way, the evaluation of `filter ()`
was also the opposite ... orz)
~~ Yes. It's an infinite loop. ~~
~~ Infinite Stream VS `Stream # filter`
I was stupid when I challenged the reckless battle. ~~
~~ When trying to avoid an infinite loop ~~
LocalDate startYmd; //Starting date
Stream.iterate(startYmd, ymd -> ymd.plusDays(5))
.limit(ChronoUnit.DAYS.between(startYmd, LocalDate.now())) // ÷5+1 is fine...
.filter(ymd -> ymd.isBefore(LocalDate.now()))
.sorted()
.findFirst()
.ifPresent(ymd -> {
System.out.println(ymd); //The first day after Today, which is 5 days from the starting date
});
It feels like ~~, what is the original purpose? It will be a code. ~~
~~ In Java8, use the `while statement`
! !! ~~
After all it's fun to use `StreamAPI`
! !!
By the way, there is a library that realizes `Stream # takeWhile`
-like behavior, so you can use it, or you can create a `TakeWhile`
class to make similar movements, so there is a degree of freedom. Is it okay to try it in high development?
Recommended Posts