Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to merge the keys of two maps?

Tags:

java

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 writes some custom code?

like image 295
Jame Avatar asked Dec 27 '22 13:12

Jame


2 Answers

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()

like image 54
NullUserException Avatar answered Jan 05 '23 13:01

NullUserException


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.

like image 45
AHungerArtist Avatar answered Jan 05 '23 13:01

AHungerArtist