List<map<String,Object>下划线转驼峰
方案一:创建新的 Map(推荐)
List<Map<String, Object>> maps = projectMapper.photovoltaicQueryBySectionId(tableNameByProductId, sectionId);List<Map<String, Object>> result = maps.stream().map(originalMap -> {Map<String, Object> newMap = new LinkedHashMap<>();originalMap.forEach((key, value) -> {String camelKey = underlineToCamel(key);newMap.put(camelKey, value);});return newMap;}).collect(Collectors.toList());
方案二:原地修改(需要小心处理)
List<Map<String, Object>> maps = projectMapper.photovoltaicQueryBySectionId(tableNameByProductId, sectionId);// 先收集所有需要修改的键值对,再统一处理
maps.forEach(map -> {Map<String, Object> temp = new HashMap<>();// 先收集转换后的键值对map.forEach((key, value) -> {String camelKey = underlineToCamel(key);temp.put(camelKey, value);});// 清空原map并放入转换后的数据map.clear();map.putAll(temp);
});
方案三:使用 Iterator 安全删除(如果你确实需要原地修改)
List<Map<String, Object>> maps = projectMapper.photovoltaicQueryBySectionId(tableNameByProductId, sectionId);maps.forEach(map -> {Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();Map<String, Object> newEntries = new HashMap<>();while (iterator.hasNext()) {Map.Entry<String, Object> entry = iterator.next();String camelKey = underlineToCamel(entry.getKey());newEntries.put(camelKey, entry.getValue());iterator.remove(); // 安全删除原条目}map.putAll(newEntries);
});
推荐使用方案一
因为它:
- 避免并发修改异常
- 代码更清晰
- 不会意外修改原始数据结构
- 符合函数式编程的无副作用原则
完整的工具方法
public List<Map<String, Object>> convertToCamelCase(List<Map<String, Object>> maps) {if (maps == null) {return new ArrayList<>();}return maps.stream().map(originalMap -> {Map<String, Object> newMap = new LinkedHashMap<>();originalMap.forEach((key, value) -> {String camelKey = underlineToCamel(key);newMap.put(camelKey, value);});return newMap;}).collect(Collectors.toList());
}private String underlineToCamel(String str) {if (str == null || str.isEmpty()) {return str;}StringBuilder result = new StringBuilder();boolean nextUpperCase = false;for (int i = 0; i < str.length(); i++) {char currentChar = str.charAt(i);if (currentChar == '_') {nextUpperCase = true;} else {if (nextUpperCase) {result.append(Character.toUpperCase(currentChar));nextUpperCase = false;} else {result.append(currentChar);}}}return result.toString();
}