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

Phil
  • 7,065
  • 8
  • 49
  • 91

1 Answers1

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

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
ernest_k
  • 44,416
  • 5
  • 53
  • 99