Splitting List into sublists along elements

后端 未结 13 1949
野趣味
野趣味 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:32

    Group by different token whenever you find a null (or separator). I used here a different integer (used atomic just as holder)

    Then remap the generated map to transform it into a list of lists.

    AtomicInteger i = new AtomicInteger();
    List> x = Stream.of("A", "B", null, "C", "D", "E", null, "H", "K")
          .collect(Collectors.groupingBy(s -> s == null ? i.incrementAndGet() : i.get()))
          .entrySet().stream().map(e -> e.getValue().stream().filter(v -> v != null).collect(Collectors.toList()))
          .collect(Collectors.toList());
    
    System.out.println(x);
    

提交回复
热议问题