Union of two or more (hash)maps
Posted
by
javierfp
on Stack Overflow
See other posts from Stack Overflow
or by javierfp
Published on 2011-01-15T20:27:45Z
Indexed on
2011/01/15
21:53 UTC
Read the original article
Hit count: 125
I have two Maps that contain the same type of Objects:
Map<String, TaskJSO> a = new HashMap<String, TaskJSO>();
Map<String, TaskJSO> b = new HashMap<String, TaskJSO>();
public class TaskJSO { String id; }
The map keys are the "id" properties.
a.put(taskJSO.getId(), taskJSO);
I want to obtain a list with: all values in "Map b" + all values in "Map a" that are not in "Map b".
What is the fastest way of doing this operation?
Thanks
EDIT: The comparaison is done by id. So, two TaskJSOs are considered as equal if they have the same id (equals method is overrided).
My intention is to know which is the fastest way of doing this operation from a performance point of view. For instance, is there any difference if I do the "comparaison" in a map (as suggested by Peter):
Map<String, TaskJSO> ab = new HashMap<String, TaskJSO>(a);
ab.putAll(b);
ab.values()
or if instead I use a set (as suggested by Nishant):
Set s = new Hashset();
s.addAll(a.values());
s.addAll(b.values());
© Stack Overflow or respective owner