繁体   English   中英

由于某些原因,流过滤器不起作用

[英]Stream filter is not working for some reason

我在这里的第一篇文章,对于Java(以及任何编程)来说是非常新的,您可以在下面看到:)

我需要从列表中打印出一个单词,但是由于某种原因,即使使用list()存在该单词,我的流命令也无法在使用filter()之后找到参数(字符串单词)。 (我尝试了sout()没有过滤器的整个列表,并在输入中找到了它)。

private List<String> lines;

public reviews(List<String> lines) { 
    this.lines = lines;
}

public void NumberOfWords(String theWord) {

    lines.stream()
            .map(lines -> lines.split(" "))
            .map(words -> Arrays.toString(words))
            .map(word -> word.trim().toLowerCase())
            .filter(word -> word.equals(theWord))   // Something wrong with this line?
            .forEach(word -> System.out.println(word));

}

没有流filter()的输出如下所示:

[1,一系列,逃避,证明,格言,那是什么,好,为,鹅,也是, ,为,甘德,,,一些,其中偶尔会逗乐,但绝不等于故事的大部分。 ] [4,这种安静,内省,娱乐性,独立性是值得的。 ] [1,甚至是ismail,商人,工作的粉丝,我,嫌疑人、、、、、、、、、、、、、、、、。 ] [3,a,肯定//等等........

并使用过滤器,假设我们将使用参数字:“ good ”。 它存在,但是方法不打印它。

您在这里有一个逻辑错误:

.map(words -> Arrays.toString(words))
.map(word -> word.trim().toLowerCase())

这里的第一行将返回数组的字符串表示形式,因此结果将类似于: “我是新手!” 改为“我是新手!” 然后,修剪此字符串将得到相同的字符串-> “ I,am,a,newbie,!” 之后,您将这个完全相同的字符串(组成一个,而不是一个简单的单词)过滤到关键字中。 最后将导致一个空列表。

如果您希望每次出现匹配项时都打印匹配的单词,则可以按以下方式使用flatMap进行打印:

lines.stream()
    .map(line -> line.split(" "))
    .flatMap(Arrays::stream)
    .map(word -> word.trim().toLowerCase())
    .filter(word -> word.equals(theWord))
    .forEach(System.out::println);

而且,如果您想打印出所需单词的全部出现,只需使用此单词:

System.out.println(lines.stream()
    .map(line -> line.split(" "))
    .flatMap(Arrays::stream)
    .map(word -> word.trim().toLowerCase())
    .filter(word -> word.equals(theWord))
    .count());

您未过滤的输出说明了一切。 您无意间比较了整个单词数组而不是一个单词的字符串。

问题在于映射到Arrays.toString(words) 在这种情况下,您的信息流中的每个元素都将变成类似于以下内容的字符串: [1, a, series, of, escapades, demonstrating, the, adage, that, what, is, good, for, the, goose, is, also, good, for, the, gander, ,, some, of, which, occasionally, amuses, but, none, of, which, amounts, to, much, of, a, story, . ] [1, a, series, of, escapades, demonstrating, the, adage, that, what, is, good, for, the, goose, is, also, good, for, the, gander, ,, some, of, which, occasionally, amuses, but, none, of, which, amounts, to, much, of, a, story, . ] (这是一个元素。)

取而代之的是,您正在寻找将单词行flatMap为单个单词的方法,如下所示:

 lines.stream()                                     // Stream each line (each line is a string)
        .map(line -> line.split(" "))               // Map to an array of words per line
        .flatMap(lineArr -> Arrays.stream(lineArr)) // Map each word array into a stream of single words, and flatten each stream into a single one
        ...                                         // Now you can work with a stream of "single words"

注意,上面的“单个单词”是指两个空格之间的任何内容。 如您在上面的数组示例中看到的,您有一些空的或仅标点符号的条目,但这不会影响您以后的equals比较。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM