Reputation: 554
I want to store objects of class from arraylist to hashmap, one key may contain multiple objects, how to do that
here is my code,
Map<Integer, classObject> hashMap = new HashMap<Integer, classObject>();
for(int i=0; i<arraylist.size(); i++)
{
sortID = arraylist.get(i).getID();
if(!hashMap.containsKey(sortID))
{
hashMap.put(sortID, arraylist.get(i));
}
hashMap.get(sortID).add(arraylist.get(i)); //i got error in add method
}
give any idea to add classobjects in hashmap for same key value...
Upvotes: 0
Views: 5462
Reputation: 30875
If you are allowed to use 3rd part libraries i strongly recomned usage of Guava and Multimap.
Upvotes: 0
Reputation: 939
Using a set or arraylist as a value most of the time seems like a bit of overhead and not easy maintainable. An elegant solution to this would be using Google Guava's MultiMap.
I suggest reading through the API of the MultiMap interface: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html
An example:
ListMultimap<String, String> multimap = ArrayListMultimap.create();
for (President pres : US_PRESIDENTS_IN_ORDER) {
multimap.put(pres.firstName(), pres.lastName());
}
for (String firstName : multimap.keySet()) {
List<String> lastNames = multimap.get(firstName);
out.println(firstName + ": " + lastNames);
}
would produce output such as:
John: [Adams, Adams, Tyler, Kennedy]
Upvotes: 1
Reputation: 7854
you can try:
Map<Integer, List<classObject>> hashMap = new HashMap<Integer, List<classObject>>();
for(int i=0; i<arraylist.size(); i++)
{
sortID = arraylist.get(i).getID();
List<classObject> objectList = hashMap.get(sortID);
if(objectList == null)
{
objectList = new ArrayList<>();
}
objectList.add(arraylist.get(i));
hashMap.put(sortID, objectList);
}
Upvotes: 3
Reputation: 6640
In a key value pair, every key refers to one and only one object. That's why it's called a key.
However, if you need to store multiple objects for the same key you can create a List
and store it with a single key. Something like this:
HashMap<Key, ArrayList<Object>>
Upvotes: 1
Reputation: 15092
The only way to do that is to have your value be a list of your objects and to add to that list when you find a dup.
Upvotes: 0
Reputation: 6812
What you can do is to map key with list of objects i.e.
Map<Integer, ArrayList<Class>> hashMap = new HashMap<Integer, ArrayList<Class>>();
and then to add a new object you can do:
hashMap.get(sortID).add(classObject);
Upvotes: 1