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:
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!