Java Streams TakeUntil 100 Elements filtered/collected
Asked Answered
S

1

5

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()) ?

Staciestack answered 9/10, 2018 at 13:39 Comment(0)
S
9

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).

Stoneblind answered 9/10, 2018 at 13:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.