I have a similar use case to this stack overflow question and was trying to use it without storing the result in a List<List<String>>
but instead call stream()
on it.
I have a strange compile time error if I don't assign it to List<List<String>>
because of type mismatch. To reproduce the issue, just comment out the assignment to output.
The question is why is this compile error occurs? And how to fix it?
public static void main(String args[]) {
List<String> input = Arrays.asList("RED", "RED", "BLUE", "BLUE", "BLUE", "BLUE", "RED", "RED");
List<List<String>> output = // if this line commented it doesn't compile
input.stream()
.collect(Collector.of(
ArrayList::new,
(accumulator, item) -> {
if (accumulator.isEmpty()) {
List<String> list = new ArrayList<>();
list.add(item);
accumulator.add(list);
} else {
List<String> last = accumulator.get(accumulator.size() - 1);
if (last.isEmpty() || last.get(0).equals(item)) {
last.add(item);
} else {
List<String> list = new ArrayList<>();
list.add(item);
accumulator.add(list);
}
}
},
(left, right) -> {
left.addAll(right);
return left;
}
));
}
My idea was to use it like:
input.stream()
.collect(Collector.of(.....))
.stream()
.(and do something else)
>`
– bbKing Sep 09 '22 at 20:28