使用流API;一旦过滤了相关数据,我想编辑正在收集的数据。以下是目前为止的代码:
String wordUp = word.substring(0,1).toUpperCase() + word.substring(1);
String wordDown = word.toLowerCase();
ArrayList<String> text = Files.lines(path)
.parallel() // Perform filtering in parallel
.filter(s -> s.contains(wordUp) || s.contains(wordDown) && Arrays.asList(s.split(" ")).contains(word))
.sequential()
.collect(Collectors.toCollection(ArrayList::new));编辑下面的代码是可怕的,我试图避免它。(它也不完全工作。它是凌晨4点做的,请原谅。)
for (int i = 0; i < text.size(); i++) {
String set = "";
List temp = Arrays.asList(text.get(i).split(" "));
int wordPos = temp.indexOf(word);
List<String> com1 = (wordPos >= limit) ? temp.subList(wordPos - limit, wordPos) : new ArrayList<String>();
List<String> com2 = (wordPos + limit < text.get(i).length() -1) ? temp.subList(wordPos + 1, wordPos + limit) : new ArrayList<String>();
for (String s: com1)
set += s + " ";
for (String s: com2)
set += s + " ";
text.set(i, set);
}它正在查找文本文件中的特定单词,一旦行被过滤,我希望每次只收集一行的一部分。正在搜索的关键字的两边的多个单词。
例:
keyword = "the" limit = 1
它会发现:"Early in the morning a cow jumped over a fence."
然后它应该返回:"in the morning"
*P.S.任何建议的速度改进都将得到表决。
发布于 2015-03-09 14:05:36
有两种不同的任务你应该考虑。首先,将一个文件转换为一个单词列表:
List<String> words = Files.lines(path)
.flatMap(Pattern.compile(" ")::splitAsStream)
.collect(Collectors.toList());这使用了在空间字符处拆分的最初想法。对于简单的任务来说,这可能就足够了,但是,您应该学习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());https://stackoverflow.com/questions/28942076
复制相似问题