我正在使用这种方法,该方法采用多个列表,其中包含书籍行。我将它们组合成一个流,然后迭代它们以拆分所有非字母的 \\P{L}
。
有没有办法避免 for-each 循环并在流中处理它?
private List<String> getWordList(List<String>... lists) {
List<String> wordList = new ArrayList<>();
Stream<String> combinedStream = Stream.of(lists)
.flatMap(Collection::stream);
List<String> combinedLists = combinedStream.collect(Collectors.toList());
for (String line: combinedLists) {
wordList.addAll(Arrays.asList(line.split("\\P{L}")));
}
return wordList;
}
最佳答案
有了流,你可以简单地进一步“flatMap
”并返回结果:
return combinedStream
.flatMap(str -> Arrays.stream(str.split("\\P{L}")))
.collect(Collectors.toList());
总而言之:
private List<String> getWordList(List<String>... lists) {
return Stream.of(lists)
.flatMap(Collection::stream)
.flatMap(str -> Arrays.stream(str.split("\\P{L}")))
.collect(Collectors.toList());
}
关于java - 在 Java 中使用流拆分单词列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54969012/