首页 > 解决方案 > 将一个 hashmap 列表连接成一个与它们相同的 otder 并且不覆盖密钥

问题描述

我正在学习 Java 语言并找到了这个练习。我知道他们想以相同的顺序将 hashmap 列表连接到一个 hashmap 中并且不覆盖密钥,但是我不理解这些示例,所以我没有像他们所说的那样在其中找到安排,所以我认为我的理解是错误的. 你能向我解释一下他们是如何工作的吗?

连接映射

该函数将被赋予一个称为地图列表的参数。地图列表是地图的列表。您的工作是将地图列表中找到的所有地图组合成一个地图并将其返回。向地图添加值有两个规则。

您必须按照它们在地图列表中的相同顺序将键值对添加到地图中。如果密钥已经存在,则无法覆盖。换句话说,如果两个或多个map具有相同的key,则要添加的key不能被后续的map覆盖。
签名:

public static HashMap<String, Integer> concatenateMap(ArrayList<HashMap<String, Integer>> mapList)

例子:

INPUT: [{b=55, t=20, f=26, n=87, o=93}, {s=95, f=9, n=11, o=71}, {f=89, n=82, o=29}]
OUTPUT: {b=55, s=95, t=20, f=26, n=87, o=93}
INPUT: [{v=2, f=80, z=43, k=90, n=43}, {d=41, f=98, y=39, n=83}, {d=12, v=61, y=44, n=30}]
OUTPUT: {d=41, v=2, f=80, y=39, z=43, k=90, n=43}
INPUT: [{p=79, b=10, g=28, h=21, z=62}, {p=5, g=87, h=38}, {p=29, g=44, x=59, y=8, z=82}]
OUTPUT: {p=79, b=10, g=28, h=21, x=59, y=8, z=62}

标签: javavariable-assignment

解决方案


public static void main(String[] args) {

    //{b=55, t=20, f=26, n=87, o=93}, {s=95, f=9, n=11, o=71}, {f=89, n=82, o=29}
    HashMap<String, Integer> map1 = new HashMap<>();
    map1.put("b", 55);
    map1.put("t", 20);
    map1.put("f", 26);
    map1.put("n", 87);
    map1.put("o", 93);

    HashMap<String, Integer> map2 = new HashMap<>();
    map2.put("s", 95);
    map2.put("f", 9);
    map2.put("n", 11);
    map2.put("o", 71);

    HashMap<String, Integer> map3 = new HashMap<>();
    map3.put("f", 89);
    map3.put("n", 82);
    map3.put("o", 29);

    ArrayList<HashMap<String, Integer>> list = new ArrayList<>();
    list.add(map1);
    list.add(map2);
    list.add(map3);

    HashMap<String, Integer> flat = concatenateMap(list);

    System.out.println(flat.toString());

}

public static HashMap<String, Integer> concatenateMap(ArrayList<HashMap<String, Integer>> mapList){

    HashMap<String, Integer> result = new HashMap<>();

    //iterate all maps
    for(HashMap<String, Integer> map : mapList){

        //iterate all keys from map
        for(String key : map.keySet()){

            //if result already contains key, skip
            if(result.containsKey(key)){
                continue;
            }

            result.put(key, map.get(key));

        }

    }

    return result;

}

推荐阅读