可以通过已知的空字符串作为分隔符将列表拆分为子列表:
List<String> data = Arrays.asList("a", "b", "c", "", "d", "", "e", "f");
int[] indexes =
Stream.of(
IntStream.of(-1),
IntStream.range(0, data.size()).filter(i -> data.get(i).isEmpty()),
IntStream.of(data.size())
)
.flatMapToInt(ix -> ix)
.toArray();
List<List<String>> subSets =
IntStream.range(0, indexes.length - 1)
.mapToObj(i -> data.subList(indexes[i] + 1, indexes[i + 1]))
.collect(Collectors.toList());
subSets.forEach(System.out::println);
输出是:
[a, b, c]
[d]
[e, f]
或者可以通过重新加入和重新拆分输入数据来实现(如果输入为List<String>):
List<String> data = Arrays.asList("a", "b", "c", "", "d", "", "e", "f");
Arrays.stream(
data.stream()
.collect(Collectors.joining("\n")).split("\n{2}") // split by double 'empty lines'
)
.map(s -> Arrays.stream(s.split("\n")).collect(Collectors.toList()))
.collect(Collectors.toList())
.forEach(System.out::println);
输出同上。