A story that I wanted to write a process equivalent to a while statement with the Stream API of Java8

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. ~~

Conclusion

~~ In Java8, use the `while statement`! !! ~~ After all it's fun to use `StreamAPI`! !!

Serpentine

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

A story that I wanted to write a process equivalent to a while statement with the Stream API of Java8
I want to write a loop that references an index with Java 8's Stream API
A story about hitting the League Of Legends API with JAVA
A story that I was addicted to twice with the automatic startup setting of Tomcat 8 on CentOS 8
I tried to make a program that searches for the target class from the process that is overloaded with Java
I tried to make a product price comparison tool of Amazon around the world with Java, Amazon Product Advertising API, Currency API (2017/01/29)
[java8] To understand the Stream API
The story I wanted to unzip
[Java] Dealing with the situation where the program that writes to the Output Stream of Process does not end even if waitFor
The story of Collectors.groupingBy that I want to keep for posterity
A story that struggled with the introduction of Web Apple Pay
A story that I finally understood Java for statement as a non-engineer
How to deal with the type that I thought about writing a Java program for 2 years
I tried to summarize the Stream API
The story of making a game launcher with automatic loading function [Java]
A story I was addicted to when testing the API using MockMVC
I tried to make a Web API that connects to DB with Quarkus
How to convert an array of Strings to an array of objects with the Stream API
After all I wanted to preview the contents of mysql with Docker ...
[Kotlin] I wanted to generate a png with a large capacity per area [Java]
I tried to solve 10 selected past questions that should be solved after registering with AtCoder with Java, Stream API
I tried to implement a function equivalent to Felica Lite with HCE-F of Android
What I tried when I wanted to get all the fields of a bean
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
I tried to create a method to apply multiple filters at once with Java Stream API. Is this okay?
When I wanted to create a method for Premium Friday, it was already in the Java 8 standard API
[Small story] I tried to make the java ArrayList a little more convenient
I tried to break a block with java (1)
[Ruby] I want to make a program that displays today's day of the week!
I wrote a test code (Junit & mockit) for the code that calls the AWS API (Java)
Write a test by implementing the story of Mr. Nabeats in the world with ruby
Let's implement a function to limit the number of access to the API with SpringBoot + Redis
[Java] The problem that true was returned as a result of comparing Integer with ==
I tried what I wanted to try with Stream softly.
How to write Scala from the perspective of Java
Use Java lambda expressions outside of the Stream API
The story of making a reverse proxy with ProxyServlet
Java: Use Stream to sort the contents of the collection
The story of making dto, dao-like with java, sqlite
Java: A story that made me feel uncomfortable when I was taught to compare strings with equals for no reason.
A note that I had trouble when trying to use nginx with Remote-Containers of vscode
The story of building a Java version of Minecraft server with GCP (and also set a whitelist)
Implemented a strong API for "I want to display ~~ on the screen" with simple CQRS
[Java] I tried to make a rock-paper-scissors game that beginners can run on the console.
I want to return a type different from the input element with Java8 StreamAPI reduce ()
A story that I realized that I had to study as an engineer in the first place
I made a program in Java that solves the traveling salesman problem with a genetic algorithm
A story I was addicted to with implicit type conversion of ActiveRecord during unit testing
[Java] Change the process according to the situation with the Strategy pattern
I tried to create a java8 development environment with Chocolatey
Story of making a task management application with swing, java
I tried to modernize a Java EE application with OpenShift.
I tried to summarize the basics of kotlin and java
20190803_Java & k8s on Azure The story of going to the festival
A story packed with the basics of Spring Boot (solved)
I want to make a list with kotlin and java!
I just wanted to make a Reactive Property in Java
I want to make a function with kotlin and java!
I want to use the Java 8 DateTime API slowly (now)
A story addicted to toString () of Interface proxied with JdkDynamicAopProxy
What I was addicted to with the Redmine REST API