[英]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.