0

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...

6 Answers 6

3

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);
    }
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

1

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]

Comments

0

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.

Comments

0

If you are allowed to use 3rd part libraries i strongly recomned usage of Guava and Multimap.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.