开发者

Java: How to merge the keys of two maps?

I am working in Java, and have declared two maps as follow:

private Map<MyCustomClass, Integer> map1, map2;
map1 = new HashMap<MyCustomClass, Integer>();
map2 = new HashMap<MyCustomClass, Integer>();

//adding some key value pair into map1
//adding some key value pair into map2

private ArrayList<MyCustomClass> list = new ArrayList<MyCustomClass>(); 

Now i want to insert the keys of both map in the above declared ArrayList. Is there any built-in method exist for this or i need to w开发者_如何学运维rites some custom code?


To add everything:

list.addAll(map1.keySet());
list.addAll(map2.keySet());

To add only unique keys:

Set<MyCustomClass> keys = new HashSet(map1.keySet());
keys.addAll(map2.keySet());

list.addAll(keys);

References: List.addAll(Collection c); HashMap.keySet()


list.addAll(map1.keySet()); 
list.addAll(map2.keySet()); 

keySet() gets all the keys from the map and returns them as a set. The addAll then adds that set to your list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜