import java.util.*;
import java.util.stream.Collectors;
public class MapKeyReplacement {
public static void main(String[] args) {
// 假设我们有如下的List<Map<String, String>>
List<Map<String, String>> list = Arrays.asList(
new HashMap<String, String>() {{
put("a", "1");
put("c", "3");
}},
new HashMap<String, String>() {{
put("a", "2");
put("d", "4");
}},
new HashMap<String, String>() {{
put("a", "5");
put("e", "6");
}}
);
Map<String, String> replaceMap = new HashMap<>();
replaceMap.put("a", "x");
replaceMap.put("c", "y");
replaceMap.put("d", "z");
replaceMap.put("f", "yy");
List<Map<String, String>> newList = list.stream()
.map(originalMap -> {
Map<String, String> newMap = new LinkedHashMap<>();
originalMap.forEach((key, value) -> {
newMap.put(replaceMap.getOrDefault(key, key), value);
});
return newMap;
})
.collect(Collectors.toList());
// 输出替换后的List<Map<String, String>>
newList.forEach(System.out::println);
}
}
标签:replaceMap,Map,java,HashMap,key,put,new
From: https://www.cnblogs.com/iullor/p/18044213