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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With