代码之家  ›  专栏  ›  技术社区  ›  Warosaurus

Java 8 Streams修改集合值

  •  0
  • Warosaurus  · 技术社区  · 10 年前

    使用流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.任何建议的速度改进都将通过投票。

    1 回复  |  直到 10 年前
        1
  •  7
  •   Holger    9 年前

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

    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());
    
    推荐文章
    twenty7  ·  按阵列列表分组
    9 年前