Andrew Andrew - 1 month ago 7
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

MyList.stream()
.filter(x -> predicate(x))
.findFirstN(100)


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
MyList.stream()
  .filter(x -> predicate(x))
  .limit(100)