簡體   English   中英

使用 Streams 將字符串與字符串數組的每個元素進行比較

[英]Compare String with each element of a String Array using Streams

嗨,我想計算使用 Streams 在String數組中找到字符串的次數

到目前為止我的想法是這樣的:

Stream<String> stream=Arrays.stream(array);

int counter= (int) stream.filter(c-> c.contains("something")).count();

return counter;

我得到的問題是,大多數時候我得到一個NullPointerException錯誤,我認為是因為.count()如果它在filter(c-> c.contains("something")) . 我得出了這個結論,因為如果我在沒有 .count .count()的情況下運行它,就像stream.filter(c-> c.contains("something")); 不返回任何內容,它不會拋出Exception 我不確定,但這就是我的想法。

關於如何計算字符串出現的次數和使用 Streams 的字符串數組的任何想法?

null是數組的有效元素,因此您必須准備好處理這些。 例如:

int counter = stream.filter(c -> c != null && c.contains("something")).count();

我得到的問題是,大多數時候我得到一個 NullPointerException 錯誤,我認為是因為.count() 而我得出這個結論是因為如果我用 out.count() 運行它,它不會拋出例外。

不調用count就無法復制NullPointerException的原因是因為流是惰性評估的,即整個管道在調用急切操作(觸發管道處理的操作)之前不會執行。

We can come to the conclusion that Arrays.stream(array) is not the culprit for the NullPointerException because it would have blown up regardless of wether you called an eager operation on the stream or not as the parameter to Arrays.stream should be nonNull or否則它會因上述錯誤而崩潰。

因此,我們可以得出結論,數組中的元素是您說明的代碼中此錯誤的罪魁禍首,但是您應該問自己首先是否允許 null 元素,如果是,則在執行之前將它們過濾掉c.contains("something")如果沒有,那么您應該調試應用程序中的哪個點將空值添加到數組中,而它們不應該添加到數組中。 找到錯誤而不是壓制它。

如果首先允許空值,那么解決方案很簡單,即在調用.contains之前過濾掉空值:

int counter = (int)stream.filter(Objects::nonNull)
                         .filter(c -> c.contains("something")) // or single filter with c -> c != null && c.contains("something") as pred
                         .count();

您必須首先過濾null值。 以@pafauk 的方式進行。 回答或通過單獨過濾。 這需要在您已經使用的過濾器之前應用null過濾器:

public static void main(String[] args) {
    List<String> chainedChars = new ArrayList<>();
    chainedChars.add("something new");  // match
    chainedChars.add("something else"); // match
    chainedChars.add("anything new");
    chainedChars.add("anything else");
    chainedChars.add("some things will never change");
    chainedChars.add("sometimes");
    chainedChars.add(null);
    chainedChars.add("some kind of thing");
    chainedChars.add("sumthin");
    chainedChars.add("I have something in mind");   // match
    chainedChars.add("handsome thing");

    long somethings = chainedChars.stream()
                                    .filter(java.util.Objects::nonNull)
                                    .filter(cc -> cc.contains("something"))
                                    .count();

    System.out.printf("Found %d somethings", somethings);
}

輸出

Found 3 somethings

而切換過濾器行將導致NullPointerException

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM