Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Streams TakeUntil 100 Elements filtered/collected

I want to use streams like:

List<String> result = myArr
    .stream()
    .filter(line -> !"foo".equals(line))
    .collect(Collectors.toList());

but stop the filtering as soon as I have maximum 100 Elements ready to be collected. How can I achieve this without filtering all and calling subList(100, result.size()) ?

like image 434
Phil Avatar asked Oct 09 '18 13:10

Phil


1 Answers

You can use limit after filter:

List<String> result = myArr
    .stream()
    .filter(line -> !"foo".equals(line))
    .limit(100) 
    .collect(Collectors.toList());

This will stop the stream after 100 items have been found after filtering (limit is a short-circuiting stream operation).

like image 90
ernest_k Avatar answered Sep 20 '22 12:09

ernest_k