Yes, there is a lambda way, but, unfortunately, I do not think that it is implemented in the current Java 8 Stream API. Sorry to point to another language, but what I think you want is something like
takeWhile(p: (A) β Boolean): Stream[A]
from the Scala Stream API.
Since this is not implemented in the Java API, you must do it yourself. How about this:
public static List<T> takeWhile(Iterable<T> elements, Predicate<T> predicate) { Iterator<T> iter = elements.iterator(); List<T> result = new LinkedList<T>(); while(iter.hasNext()) { T next = iter.next(); if (predicate.apply(next)) { result.add(next); } else { return result; // Found first one not matching: abort } } return result; // Found end of the elements }
Then you can use it as
List<Long> fibNumbersUnderThousand = takeWhile(allFibNumStream, l -> l < 1000);
(Assuming Stream is an Iterable instance - if not, you might need to call the .iterator() method and end it)
source share