首页 > 解决方案 > 我们可以在 Java 8 中迭代时修改 Map 值吗

问题描述

我有一个Map<Integer,String>. 我需要能够先过滤掉偶数的键,然后迭代映射值并修改映射值的内容。我尝试运行下面的代码,但值没有改变。java 8中是否可以在迭代a时根据某些条件修改值Map

Map<Integer,String> m = new HashMap<>();
    m.put(1,"ABC");
    m.put(2,"PQR");
    m.put(3,"XYZ");
    m.put(4,"RST");

Map<Integer,String> m1 =  m.entrySet().stream()
    .filter(map -> map.getKey().intValue() %2 == 0)
    .collect(Collectors.toMap(
        map -> map.getKey(),map -> map.getValue()));
            Map<Integer,String> m3 = m1.entrySet().stream()
                .filter(m2 -> {
                    if(m2.getValue().equalsIgnoreCase("PQR")){
                        m2.getValue().replace("PQR","PQR1");
                    } else if(m2.getValue().equalsIgnoreCase("RST")) {
                        m2.getValue().replace("RST", "RST1");
                    }
                    return true;
                }).collect(Collectors.toMap(m2 -> m2.getKey(), m2 -> m2.getValue()));

System.out.println(m3);

我得到的答案是,{2=PQR, 4=RST}但我的答案应该是{2=PQR1, 4=RST1}

标签: javadictionarylambdajava-8java-stream

解决方案


问题出在replace方法上:由于String是不可变的,所以这个方法返回一个新的字符串。但是代码忽略了这个返回值。

为了对您的代码进行最小程度的调整,请m3像这样创建地图:

    Map<Integer,String> m3 = m1.entrySet().stream().map(m2 -> {
        if(m2.getValue().equalsIgnoreCase("PQR")){
            m2.setValue("PQR1");
        }else if(m2.getValue().equalsIgnoreCase("RST")) {
            m2.setValue("RST1");
        }
        return m2;
    }).collect(Collectors.toMap(m2 -> m2.getKey(), m2 -> m2.getValue()));

推荐阅读