Splitting List into sublists along elements

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

    This is a very interesting problem. I came up with a one line solution. It might not very performant but it works.

    List<String> list = Arrays.asList("a", "b", null, "c", null, "d", "e");
    Collection<List<String>> cl = IntStream.range(0, list.size())
        .filter(i -> list.get(i) != null).boxed()
        .collect(Collectors.groupingBy(
            i -> IntStream.range(0, i).filter(j -> list.get(j) == null).count(),
            Collectors.mapping(i -> list.get(i), Collectors.toList()))
        ).values();
    

    It is a similar idea that @Rohit Jain came up with. I'm grouping the space between the null values. If you really want a List<List<String>> you may append:

    List<List<String>> ll = cl.stream().collect(Collectors.toList());
    
    0 讨论(0)
提交回复
热议问题