Home >Java >javaTutorial >How Can I Limit an Infinite Java 8 Stream Based on a Predicate?

How Can I Limit an Infinite Java 8 Stream Based on a Predicate?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-26 13:40:10556browse

How Can I Limit an Infinite Java 8 Stream Based on a Predicate?

Java 8: Implementing Stream Limiting Based on Predicate Match

Java 8 lacks a specific stream operation that limits a potentially infinite stream until an element fails to match a given predicate. While Java 9 introduces the takeWhile operation for this purpose, Java 8 users seek alternative implementation strategies.

Solution in Java 8

To implement predicate-based stream limiting in Java 8, the following approach can be employed:

  • Create an Infinite Stream: Utilize Stream.iterate or Stream.generate to create an infinite stream of values.
  • Use limit and filter Operations: Apply the limit operation with an arbitrary limit (such as Long.MAX_VALUE) to avoid infinite iteration. Then, use filter to evaluate the predicate for each element. This ensures that iteration continues until the predicate fails.

Example:

IntStream.iterate(1, n -> n + 1)
    .limit(Long.MAX_VALUE)
    .filter(n -> n < 10)
    .forEach(System.out::println);

Java 9 and Beyond

If using Java 9 or later, the takeWhile operation simplifies the implementation:

IntStream.iterate(1, n -> n + 1)
    .takeWhile(n -> n < 10)
    .forEach(System.out::println);

The above is the detailed content of How Can I Limit an Infinite Java 8 Stream Based on a Predicate?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn