循环中使用Stream Filter对比数组元素报错:变量需为final或有效final
循环中使用Stream Lambda报错的解决方法
错误原因
Java Lambda表达式要求引用的外部局部变量必须是final或有效final(即变量初始化后不再被修改)。你循环中的x每次迭代都会改变值,不符合这个规则,因此触发local variable x defined in an enclosing scope must be final or effectively final错误。
方案一:提取局部变量适配Lambda要求
在循环内部,将当前要匹配的cp[x]赋值给一个新的局部变量,这个变量在单次迭代中不会被修改,属于有效final,可正常在Lambda中使用:
public static boolean getReturnOrigin(List<Character> list) { int[] counts = {0,0,0,0}; char [] cp = {'n', 's', 'e', 'w'}; for(int x = 0; x<counts.length; x++) { char targetChar = cp[x]; // 提取为有效final的局部变量 counts[x] = (int) list.stream() .filter(i -> i == targetChar) .count(); } // 补充回到原点的判断逻辑:n与s数量相等,e与w数量相等 return counts[0] == counts[1] && counts[2] == counts[3]; }
方案二:用Stream一次性统计(更高效简洁)
无需循环调用Stream,直接通过Collectors统计所有字符的出现次数,再填充到数组中,更符合Stream的设计理念:
import java.util.Map; import java.util.stream.Collectors; public static boolean getReturnOrigin(List<Character> list) { char [] cp = {'n', 's', 'e', 'w'}; // 一次性统计所有字符的出现次数 Map<Character, Long> charCountMap = list.stream() .collect(Collectors.groupingBy(c -> c, Collectors.counting())); int[] counts = new int[cp.length]; for(int x = 0; x<cp.length; x++) { // 从Map中取值,无对应字符则默认0 counts[x] = charCountMap.getOrDefault(cp[x], 0L).intValue(); } return counts[0] == counts[1] && counts[2] == counts[3]; }
内容的提问来源于stack exchange,提问作者Luis Fernando Chávez Morales
相关产品推荐
相关产品推荐

