Java 8 Streams修改集合值

War*_*rus 0 java java-8 java-stream collectors

使用流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));
Run Code Online (Sandbox Code Playgroud)

编辑下面的代码很糟糕,我试图避免它.(它也没有完全奏效.它是在凌晨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);
    }
Run Code Online (Sandbox Code Playgroud)

它正在寻找文本文件中的特定单词,一旦过滤了行,我只想每次都收集一部分行.正在搜索的关键字两侧的大量单词.

例如:

keyword = "the" limit = 1

它会找到: "Early in the morning a cow jumped over a fence."

它应该返回: "in the morning"

*PS任何建议的速度改进将被投票.

Hol*_*ger 7

您应该考虑两个不同的任务.首先,将文件转换为单词列表:

List<String> words = Files.lines(path)
    .flatMap(Pattern.compile(" ")::splitAsStream)
    .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

这使用了您在空格字符处拆分的初步想法.这对于简单的任务可能就足够了,但是,您应该学习文档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());
Run Code Online (Sandbox Code Playgroud)

  • @Warosaurus技术上,`O(2n)= O(n)`;-) (5认同)