Splitting List into sublists along elements

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

    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]]
    

提交回复
热议问题