This is basically a follow-up of this answer of mine.
Suppose that I am working on custom collector and supposing that the accumulator
always will add some element to the collection returned by the supplier, is there any chance that when combiner
is called, one of the intermediate results will be empty? An example is probably a lot simpler to understand.
Suppose I have a List
of numbers and I want to split it in List of Lists, where 2
is the separator. So for example I have 1, 2, 3, 4, 2, 8
, the result should be [[1], [3, 4], [8]]
. This is not really complicated to achieve (don't judge the code too much, I wrote something fast, just so I could write this question).
List<List<Integer>> result = Stream.of(1, 2, 3, 4, 2, 8)
.collect(Collector.of(
() -> new ArrayList<>(),
(list, elem) -> {
if (list.isEmpty()) {
List<Integer> inner = new ArrayList<>();
inner.add(elem);
list.add(inner);
} else {
if (elem == 2) {
list.add(new ArrayList<>());
} else {
List<Integer> last = list.get(list.size() - 1);
last.add(elem);
}
}
},
(left, right) -> {
// This is the real question here:
// can left or right be empty here?
return left;
}));
This is irrelevant probably in this example, but the question is: can the one the elements in the combiner
be an empty List
? I am really really inclined to say NO
, since in the documentation these are referred as:
combiner - an associative, non-interfering, stateless function that accepts two partial result containers and merges them.
Well that partial to me is an indication that accumulator
was called on them, before they reached combiner
, but just wanted to be sure.