Java 代码优化:将 Map 中的 Key 转换为驼峰命名法
以下是优化后的代码:
public static Page<Map<String, Object>> toCamelCase(Page<Map<String, Object>> page) {
List<Map<String, Object>> records = page.getRecords();
if (records != null && !records.isEmpty()) {
List<Map<String, Object>> newRecords = new ArrayList<>(records.size());
for (Map<String, Object> record : records) {
Map<String, Object> newRecord = new HashMap<>(record.size());
for (Map.Entry<String, Object> entry : record.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
String newKey = toCamelCase(key);
newRecord.put(newKey, value);
}
newRecords.add(newRecord);
}
page.setRecords(newRecords);
}
return page;
}
主要的优化点如下:
-
为了避免频繁调用 List 的 indexOf 方法,我们改为使用一个新的 List 存储转换后的记录。这样可以避免性能问题。
-
在创建 Map 对象时,我们指定了其初始化大小,这样可以避免 Map 在插入元素时频繁扩容。
-
在转换完成后,我们直接将新的记录列表设置回 Page 对象中,这样可以避免原来记录列表中的对象被修改,导致不可预期的问题。
-
如果 Page 对象中的记录列表为 null 或者为空,则直接返回原 Page 对象,这样可以避免不必要的操作。
原文地址: http://www.cveoy.top/t/topic/lOFq 著作权归作者所有。请勿转载和采集!