Count elements from Stream but consider only N for collecting

  • A+
Category:Languages

Is the following lambda possible somehow in Java? I'd like to count elements from my filtered stream but collaterally store the first 10

stream().filter(myFilter)  //Reduces input to forthcoming operations         .limit(10)         //Limits to ten the amount of elements to finish stream          .peek(myList::add) //Stores the ten elements into a list         .count();          //Here is the difficult one. Id like to count everything  the total of elements that pass the filter, beyond the 10 I am fetching 

EDIT: It was too implicit from my side, but the idea is meant of course as a potential solution which would be the fastest (faster than calling twice the stream generator and do both operations separately at least):

List<Entity> entities = stream().filter(myFilter)                                  .limit(10)                                 .collect(Collectors.toList()); long entitiesCount = stream().filter(myFilter)                               .count(); 

... taking profit of a single iteration, and without having to load the whole collection on memory. I'm doing tests with parallelization of the answers

 


A custom collector is the answer here:

Entry<List<Integer>, Integer> result = list.stream()             .collect(Collector.of(                     () -> new SimpleEntry<>(new ArrayList<>(), 0),                     (l, x) -> {                         if (l.getKey().size() < 10) {                             l.getKey().add(x);                         }                         l.setValue(l.getValue() + 1);                     },                     (left, right) -> {                         List<Integer> leftList = left.getKey();                         List<Integer> rightList = right.getKey();                         while (leftList.size() < 10 && rightList.size() > 0) {                             leftList.add(rightList.remove(0));                         }                         left.setValue(left.getValue() + right.getValue());                         return left;                     })); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: