简体   繁体   中英

How to add multiple objects of class for same key value in HashMap in java?

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

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

What you can do is to map key with list of objects ie

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

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

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]

唯一的方法就是让您的值成为对象列表,并在找到dup时将其添加到该列表中。

如果允许使用第三部分库,我强烈建议您使用GuavaMultimap

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM