Lex*_*yte 2 java java-8 java-stream
我正在尝试使用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;
}
Run Code Online (Sandbox Code Playgroud)
有一种方法可以做你想要的而不需要保留一个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;
}
Run Code Online (Sandbox Code Playgroud)
这就像其他答案一样.唯一的区别是,我使用limit(2)到短路流,如果我们已经发现了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;
}
Run Code Online (Sandbox Code Playgroud)