java - 将一个 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}
解决方案
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;
}
推荐阅读
- android - 如何使用 RxJava 2 处理错误异常?
- javascript - 使用 reactjs 从 mongodb 获取数据时出错
- codeigniter - 如何使用 codeigniter 通过本地主机 gmail 帐户发送电子邮件
- excel - Excel VBA - 将文件夹路径分配给变量
- dask - dask.array.apply_gufunc 具有不同形状的多个输出
- teechart - 使用 teeChart 的渐进线系列动画
- javascript - 我如何在 Sequelize 中进行自我加入?
- python - 在 Spyder IDE(或 Anaconda3 Prompt)上运行 Pyinstaller
- android - 当我的应用程序运行时,我无法收到推送通知,如果它已关闭,我会收到通知
- windows - 更改服务登录 - 密码中的空格字符