Splitting List into sublists along elements

后端 未结 13 1909
野趣味
野趣味 2020-11-28 21:51

I have this list (List):

[\"a\", \"b\", null, \"c\", null, \"d\", \"e\"]

And I\'d like something like this:

13条回答
  •  一向
    一向 (楼主)
    2020-11-28 22:30

    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.

提交回复
热议问题