Java: How to combine the keys of two cards?

I work in Java and declared two maps as follows:

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 cards into the ArrayList declared above. Is there any built-in method for this or do I need to write some kind of custom code?

+4
source share
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()

+8
source
 list.addAll(map1.keySet()); list.addAll(map2.keySet()); 

keySet () receives all keys from the card and returns them as a set. AddAll then adds this set to your list.

+2
source

All Articles