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

时间:2018-08-14 12:57:38

标签: java filter java-stream

我在这里的第一篇文章,对java(以及任何编程)都是非常新的,如下所示:)

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

my_row

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

[1,a,series,of escapades,show,the,adage,that,what,is,good,for,the,the goose,also, good ,for,the ,偶尔会逗乐,但其中没有一个,相当于故事的大部分。 ] [4,这种安静,自省,娱乐性,独立性是值得的。 ] [1,甚至是ismail,商人,工作的粉丝,我,嫌疑人、、、、、、、、、、、、、、、 ] [3,肯定是 // ........

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

2 个答案:

答案 0 :(得分:3)

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

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

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

如果您希望每次出现匹配项时都打印匹配的单词,则可以按照以下方式使用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());

答案 1 :(得分:0)

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

问题出在到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, . ] (这是一个要素。)

相反,您希望将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比较。

相关问题