java 替换Map中key的值



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);
    }
}


posted @ 2024-02-29 14:55  iullor  阅读(386)  评论(0编辑  收藏  举报