I'm stuck on an edge case in java stream manipulations...
I want to code the following behavior: "From an arbitrary basket of fruits, collect the 20 smallest, except the smallest pear, because we don't want that."
Added bonus: the baskets to come might not have any pear at all.
Examples :
- From [Pear 5, Apple 1, Apple 2, Apple 10, Pear 3, Pear 7], we want [Apple 1, Apple 2, Pear 5, Pear 7, Apple 10].
- From [Apple 4, Apple 7, Pear 8, Pear 2, Pear 3], we want [Pear 3, Apple 4, Apple 7, Pear 8].
So far, I'm at this step:
output = basket.stream()
.sorted(Comparator.comparing(Fruit::getSize))
//.filter(???)
.limit(20)
.collect(fruitCollector);
This seems like a case of stateful lambda filter, and I don't know how to do that.
I can't use a local firstPear
boolean and set it to true
after filtering the first pear, since all local variables in a lambda must be final.
Worst case scenario I can split the basket in two, pears and non-pears, sort the pears, and sublist them appropriately if there is any. This seems very inefficient and ugly. Is there a better way?
[Edit] Answer comparison
There was much variety in the answers posted here, and most of them are valid. In order to give back to the community, I put together a small testing harness to compare the performance of these algorithms.
This comparison was not as extensive as I wanted - It's been 3 weeks already. It only covers usage for sequential processing of simple items. Feel free to give the testing harness a go, and add more tests, more benchmarks, or your own implementation.
My analysis:
Algorithm | Author | Perf | Comments -------------------------------------------------------------------------------- Indexed removal | Holger | Best | Best overall, somewhat obscure Stateful predicate | pedromss | Best | Do not use for parallel processing Straightforward approach | Misha | Best | Better when few elements match Custom collector | Eugene | Good | Better when all or no element match Comaprator hack w/ dummy | yegodm | Good | - Comparator hack | xenteros | * | Perf sensitive to output size, fails on edge cases.
I acecpted pedromss' answer, as it's the one we implemented in the project, due to both its good performance, and "black-box" capabilities (the state-managing code is in an external class, and contributors can focus on the business logic).
Note that the accepted answer might not be the best for you: review the others, or check my testing project to see for yourself.
k
other elements that are different from all of the others (k
in this case equal to1
) and you, in this example, want to react to them in different way. Stream can't do that.. at list not in one nice pipeline. There must be a well defined rule on what exactly is the type of problem streams are ment to solve.