在两个地图中创建或更新键值对

时间:2019-08-23 14:15:55

标签: java java-8

我有一个键值对映射,每个值都是一个键值对映射。

类似

Map<String, Map<String, Integer> outMap = new HashMap<>();

Map<String, Integer> inMap = new HashMap<>();
inMap.put("i11", 111);
inMap.put("i21", 121);
outMap.put("o1", inMap);

我将如何处理可使用Java 8在地图的两个级别上创建/更新的条目?

输入将是外键/内键和值。因此我们应该能够添加一个新条目,因为它在外部地图中不存在。如果外部地图中存在该条目,则将新条目插入内部地图(如果不存在),否则用新值更新内部地图。

2 个答案:

答案 0 :(得分:3)

您想要实现的目标可以通过以下单行代码完成:

outerMap.computeIfAbsent(outerKey, k -> new HashMap<>()).put(innerKey, value)

但是,如果没有这些方法,则只需使用get()和put()即可实现相同的目的:

Map<String, Integer> innerMap = outerMap.get(outerKey);
if (innerMap == null) {
    innerMap = new HashMap<>();
    outerMap.put(outerKey, innerMap);
}
innerMap.put(innerKey, value);

答案 1 :(得分:0)

如何在两个地图中同时更新单值和多值

NTOE: namedMap.computIfAbsent(k,Funtion)->如果给定映射中的键为null或不存在,则使用funtion计算值并将其添加到给定映射中

 Map<String, Map<String, Integer>> outMap = new HashMap<>();
        Map<String, Integer> inMap = new HashMap<>();
        inMap.put("i11", 111);
        inMap.put("i21", 121);
        outMap.put("o1", inMap);

    System.out.println(outMap.toString());
    System.out.println(inMap.toString());

更新前的输出:

{o1 = {i11 = 111,i21 = 121}}

{i11 = 111,i21 = 121}

//If you want to add one value in the inner hashmap you created:
 outMap.computeIfAbsent("newHashMapKey",k -> new HashMap<>()).put("Arpan",2345);




// if you want to add more than 1 value at a time in the inner hashmap

   outMap.computeIfAbsent("newHashMapKey2",k -> new HashMap<>()).putAll(new HashMap<String, Integer>(){{
                put("One", 1);
                put("Two", 2);
                put("Three", 3);
            }});


        System.out.println(outMap.toString());
        System.out.println(inMap.toString());

同时更新两个地图之后的输出

{o1 = {i11 = 111,i21 = 121},newHashMapKey2 = {Two = 2,Three = 3,One = 1},newHashMapKey = {Arpan = 2345}}

{i11 = 111,i21 = 121}