I have this list (List):
[\"a\", \"b\", null, \"c\", null, \"d\", \"e\"]
And I\'d like something like this:
In my StreamEx library there's a groupRuns method which can help you to solve this:
List input = Arrays.asList("a", "b", null, "c", null, "d", "e");
List> result = StreamEx.of(input)
.groupRuns((a, b) -> a != null && b != null)
.remove(list -> list.get(0) == null).toList();
The groupRuns method takes a BiPredicate which for the pair of adjacent elements returns true if they should be grouped. After that we remove groups containing nulls and collect the rest to the List.
This solution is parallel-friendly: you may use it for parallel stream as well. Also it works nice with any stream source (not only random access lists like in some other solutions) and it's somewhat better than collector-based solutions as here you can use any terminal operation you want without intermediate memory waste.