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())
?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With