List<String> nameList = new ArrayList<>(); List<Entity> rsList = new ArrayList<>(); List<List<String>> valueList = new ArrayList<>(); for (Entity e : rsList) { List<String> singleRecord = new ArrayList<>(); nameList.forEach(n -> singleRecord.add(e.get(n) == null ? "" : e.get(n).toString())); if (e.getMetadata().containsKey(ChargeConst.RATE_RULE_DETAIL)) { Set<Map<String, Object>> ruleDtls = (Set<Map<String, Object>>) e.getMetadata().get(ChargeConst.RATE_RULE_DETAIL); Map<String, Object> mergedMap = ruleDtls.stream().flatMap(map -> map.entrySet().stream()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> newValue)); singleRecord = IntStream.range(0, singleRecord.size()) .mapToObj(i -> singleRecord.get(i).equals("") && mergedMap.get(nameList.get(i)) != null ? mergedMap.get(nameList.get(i)).toString() : singleRecord.get(i)) .collect(Collectors.toList()); } valueList.add(singleRecord); } if (e.getMetadata().containsKey(ChargeConst.RATE_RULE_DETAIL)) { Set<Map<String, Object>> ruleDtls = (Set<Map<String, Object>>) e.getMetadata().get(ChargeConst.RATE_RULE_DETAIL); Map<String, Object> mergedMap = ruleDtls.stream().flatMap(map -> map.entrySet().stream()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> newValue)); System.err.println(); } 错误:Local variable singleRecord defined in an enclosing scope must be final or effectively final
时间: 2023-12-18 12:03:59 浏览: 112
这个错误是因为在lambda表达式中使用了`singleRecord`这个变量,而且它不是final或者effective final的。为了解决这个问题,你可以将`singleRecord`声明为final,或者使用一个新的列表来存储在lambda表达式中需要使用的值,而不是直接引用`singleRecord`。例如:
```
final List<String> finalSingleRecord = singleRecord;
valueList.add(IntStream.range(0, finalSingleRecord.size())
.mapToObj(i -> finalSingleRecord.get(i).equals("") && mergedMap.get(nameList.get(i)) != null ? mergedMap.get(nameList.get(i)).toString() : finalSingleRecord.get(i))
.collect(Collectors.toList()));
```
或者
```
List<String> newSingleRecord = IntStream.range(0, singleRecord.size())
.mapToObj(i -> singleRecord.get(i).equals("") && mergedMap.get(nameList.get(i)) != null ? mergedMap.get(nameList.get(i)).toString() : singleRecord.get(i))
.collect(Collectors.toList());
valueList.add(newSingleRecord);
```
阅读全文