合并Java中的地图 [英] Merge maps in java

查看:57
本文介绍了合并Java中的地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的很简单.我想合并两张地图. 说

What i'm trying to do is pretty simple.I want to merge two maps. Say

map1={(1,"one"),(2,"two"),(3,"three");
map2={(1,"onetoo"),(4,"four")};

如果我遵循此->

map3.putall(map1);
map3.putall(map2);

然后1的值也是oneone,但是当我按照相反的顺序时,它是1. 我有什么可以改变的吗?我的意思是java会覆盖并仅将键的最新值放入. 也就是说,如果将onetoo添加到一个(在各自的映射中)之后,则无论putall调用map3的顺序如何,该值都保持onetoo.

then value of 1 is onetoo but when i follow the reverse it is one. is there anyway i could change that?what i mean is that java overwrites and puts only the latest value for a key. i.e if onetoo was added after one (in their respective maps)then no matter what the order of putall calls to map3 the value remains onetoo.

推荐答案

除非您存储添加值的实际时间,否则无法做到这一点.

There is no way to do that, unless you store the actual time when the values were added.

map1={(1,("one", 15:15)), (2, ("two", 15:16))}

然后,您可以添加所有map1,然后遍历map2,仅在键不存在或键已存在但具有较早的时间戳的情况下进行迭代.

Then you can add all of map1 and then iterate over map2 adding only if the key is not already there or if it's there but with a earlier timestamp.

这篇关于合并Java中的地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆