Splitting List into sublists along elements

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

    Please do not vote. I do not have enough place to explain this in comments.

    This is a solution with a Stream and a foreach but this is strictly equivalent to Alexis's solution or a foreach loop (and less clear, and I could not get rid of the copy constructor) :

    List> result = new ArrayList<>();
    final List current = new ArrayList<>();
    list.stream().forEach(s -> {
          if (s == null) {
            result.add(new ArrayList<>(current));
            current.clear();
          } else {
            current.add(s);
          }
        }
    );
    result.add(current);
    
    System.out.println(result);
    

    I understand that you want to find a more elegant solution with Java 8 but I truly think that it has not been designed for this case. And as said by Mr spoon, highly prefer the naive way in this case.

提交回复
热议问题