我正在练习算法,我正在尝试在循环内创建一个流,其中 te 长度等于另一个数组的大小。我在那里制作了 2 个数组:counts[] 和 cp[]
public static boolean getReturnOrigin(List list) {
//list:['n', 's', 's', 'w', 'e', 'n', 'n', 'w', 'w', 'w']
// counts: {n, s, e, w}
int[] counts = {0,0,0,0};
char [] cp = {'n', 's', 'e', 'w'};
for(int x = 0; x<counts.length; x++) {
counts[x] = (int) list.stream().
filter(i -> i==cp[x])
.count();
}
return true;
}
我试图使用循环将整数存储在 counts[] 中,并在内部添加一个流。在流中我想使用过滤器与每个 cp[x] 进行比较。
但是我在 cp[x] 中收到错误,消息为“在封闭范围内定义的局部变量 x 必须是最终的或实际上是最终的”
谁能帮我解决这个问题?
就像错误消息所说的那样,您试图将局部变量传递到 lambda 表达式中,如果该变量不是最终变量或实际上最终变量,则不允许该变量。
你可以尝试修复这个问题
for(int x = 0; x<counts.length; x++) {
final int finalValue = x;
counts[x] = (int) list.stream().
filter(i -> i==cp[finalValue])
.count();
}