Reputation: 412
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;
}
Upvotes: 2
Views: 1330
Reputation: 34460
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.
Upvotes: 9
Reputation: 56423
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;
}
Upvotes: 8
Reputation: 20901
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;
}
}
Upvotes: 0