简体   繁体   English

递增IntStream外部的整数值

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

I am trying to use an IntStream to increment an int value that is outside the stream.The point of this method is to find if there are chars on same position that are not equal. 我正在尝试使用IntStream来增加流外部的int值。此方法的目的是查找相同位置上是否存在不相等的字符。 The n and word Strings are both same length. n和单词字符串的长度相同。

When I try to increment the counter in the scope of forEach it shows me that it should be final or effectively final. 当我尝试在forEach范围内递增计数器时,它向我显示它应该是最终的或有效的最终。 Anyone could suggest a better way to do this or a way to increment this counter? 任何人都可以建议一个更好的方法来做这个或增加这个计数器的方法?

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;


} 

There's a way to do what you want without needing to keep a counter variable: 有一种方法可以做你想要的而不需要保持一个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;
}

This is like other answers. 这就像其他答案一样。 The only difference is that I'm using limit(2) to short-circuit the stream if we've already found 2 different characters. 唯一的区别是,如果我们已经找到2个不同的字符,我使用limit(2)短路流。

You shouldn't use the forEach to count occurrences, rather use the built in count method. 您不应使用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;
}

You can declare counter as instance variable instead. 您可以将counter声明为实例变量。 For more, read my another answer about effectively final . 更多信息,请阅读关于有效最终的 另一个答案

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