I have this list (List):
[\"a\", \"b\", null, \"c\", null, \"d\", \"e\"]
And I\'d like something like this:
Well, after a bit of work U have come up with a one-line stream-based solution. It ultimately uses reduce() to do the grouping, which seemed the natural choice, but it was a bit ugly getting the strings into the List required by reduce:>
List> result = list.stream()
.map(Arrays::asList)
.map(x -> new LinkedList(x))
.map(Arrays::asList)
.map(x -> new LinkedList>(x))
.reduce( (a, b) -> {
if (b.getFirst().get(0) == null)
a.add(new LinkedList());
else
a.getLast().addAll(b.getFirst());
return a;}).get();
It is however 1 line!
When run with input from the question,
System.out.println(result);
Produces:
[[a, b], [c], [d, e]]