Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 stream and then sample from the result, but that doesn't take advantage of the lazy evaluation inherent to streams.

like image 581
Andrew Avatar asked Oct 26 '16 23:10

Andrew


1 Answers

MyList.stream()
  .filter(x -> predicate(x))
  .limit(100)
like image 75
infiniteRefactor Avatar answered Oct 03 '22 00:10

infiniteRefactor