你应该考虑两个不同的任务。首先,将文件转换为单词列表:
List<String> words = Files.lines(path)
.flatMap(Pattern.compile(" ")::splitAsStream)
.collect(Collectors.toList());
这使用了在空格字符处拆分的最初想法。这可能足以完成简单的任务,但是,你应该学习
the documentation of
BreakIterator
了解这种简单方法与真实、复杂的单词边界分割之间的区别。
其次,如果你有一个单词列表,你的任务是找到你的
word
并将匹配项周围的项目序列转换为单个匹配项
String
通过使用单个空格字符作为分隔符来连接单词:
List<String> matches=IntStream.range(0, words.size())
// find matches
.filter(ix->words.get(ix).matches(word))
// create subLists around the matches
.mapToObj(ix->words.subList(Math.max(0, ix-1), Math.min(ix+2, words.size())))
// reconvert lists into phrases (join with a single space
.map(list->String.join(" ", list))
// collect into a list of matches; here, you can use a different
// terminal operation, like forEach(System.out::println), as well
.collect(Collectors.toList());