简体   繁体   中英

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. The n and word Strings are both same length.

When I try to increment the counter in the scope of forEach it shows me that it should be final or effectively final. 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:

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.

You shouldn't use the forEach to count occurrences, rather use the built in count method.

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. 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM