簡體   English   中英

遞增IntStream外部的整數值

[英]Increment an integer value that is outside a IntStream

我正在嘗試使用IntStream來增加流外部的int值。此方法的目的是查找相同位置上是否存在不相等的字符。 n和單詞字符串的長度相同。

當我嘗試在forEach范圍內遞增計數器時,它向我顯示它應該是最終的或有效的最終。 任何人都可以建議一個更好的方法來做這個或增加這個計數器的方法?

public boolean check(String n,String word){
    int counter=0;

    IntStream.range(0, n.length())
        .forEach(z->{

            if(n.charAt(z)!=word.charAt(z)){
            counter++;
            }
        });
    if(counter>1)
        return false;
    else
        return true;


} 

有一種方法可以做你想要的而不需要保持一個counter變量:

public boolean check(String n, String word) {
    long count = IntStream.range(0, n.length())
        .filter(i -> n.charAt(i) != word.charAt(i))
        .limit(2) // short-circuit here!
        .count();
    return count <= 1;
}

這就像其他答案一樣。 唯一的區別是,如果我們已經找到2個不同的字符,我使用limit(2)短路流。

您不應使用forEach計算出現次數,而應使用內置count方法。

public boolean check(String n, String word){
       int counter = (int)IntStream.range(0, n.length())
                     .filter(z -> n.charAt(z) != word.charAt(z)).count();
       return counter <= 1;
}

您可以將counter聲明為實例變量。 更多信息,請閱讀關於有效最終的 另一個答案

class Test {
    private int counter = 0;
    public boolean check(String n,String word){

        IntStream.range(0, n.length())
                .forEach(z->{
                    if(n.charAt(z) != word.charAt(z)) {
                        counter++;
                    }
                });
        return counter <= 1;
    }
}

暫無
暫無

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

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