Andrew Andrew - 9 months ago 50
Java Question

findFirst() for Java streams, but for n elements?

I want to collect the first n elements from a stream, without iterating through the entire thing. Is there a standard method that does this? Ala
.filter(x -> predicate(x))

would return a collection of up to 100 elements from the stream? My alternative is to evaluate the entire string and then sample from the result, but that doesn't take advantage of the lazy evaluation inherent to streams.

Answer Source
  .filter(x -> predicate(x))