Vyas, Anirudh. I am looking to implement a Map, with 1 key and multiple Values for that Key like may be in a list?
Can someone give me a rough sketch as to how i can go about it? I just need a little skeleton of steps may be Forum: Java in General. Implementing a HashMap with multiple values for 1 key. Anirudh Vyas. Hi, I am looking to implement a Map, with 1 key and multiple Values for that Key like may be in a list? Thanks in advance guys, appreciate your help! Justin Russo.
You can implement it in this way if i understood you correctly. You Want it. Get it Regards Vyas,Anirudh. MultiValueMap is pretty cool.
HashMap with multiple values under the same key
So easy to just dump a ResultSet into it and not have to worry at all about duplicate keys!. But I found it somewhat slower. I guess the map operations its doing could be memory intensive. Before using MultivalueMap I was using the old fashioned way of jdbc loop. Getting back the data one at a time for and putting it into HashMap. I felt there had to be a better way of doing it, and I stumbled across this post.
Even though MultiValueMap does a nice job, I would be interested in seeing, how much performance would get affected, if my query returned a large resultset. To get a wish, you need a genie. To get a genie, you need a lamp. To get a lamp, lssv for sale need a tiny ad:.
Longer chain size will counter the whole purpose of using a hash structure because the goal is to come as close to O 1 as possible. You could give a shot at Guava library former Google collections. It has implementations of Multimaps which can store multiple values for a single key.
Another cool example would be SetMultimapwhich is very similar to ListMultimap except that values for a key are kept in a set. From user perspective, I don't know how exactly it is implemented. You can have as your value, some kind of Collection and use that to store as many values as you wish. But it's generally bad practice to build up generic data structures inside generic data structures.
Why not write a domain-specific class that wraps the HashMapand makes it easier for you to check for existence of a value, number of items per key, etc? Learn more. Asked 7 years, 6 months ago. Active 2 years, 2 months ago. Viewed 28k times. Is it possible to keep multiple values corresponding to a key in a HashMap?
If yes, how? DNA Anand Anand 17k 40 40 gold badges silver badges bronze badges. Active Oldest Votes. Steve Kuo Iulian Popescu 2, 4 4 gold badges 17 17 silver badges 27 27 bronze badges. Ivan Koblik Ivan Koblik 4, 1 1 gold badge 25 25 silver badges 31 31 bronze badges. Fouad Eng. Fouad k 61 61 gold badges silver badges bronze badges. For example, Set. Or just plain old array. Strictly speaking, no. Argyle Argyle 3, 18 18 silver badges 37 37 bronze badges. Craig Otis Craig Otis Sign up or log in Sign up using Google.
Sign up using Facebook. Sign up using Email and Password. Post as a guest Name. Email Required, but never shown. The Overflow Blog.Comment 8. HashMap can be used to store key-value pairs. But sometimes you may want to store multiple values for the same key.
The following code snippets will show you three different ways of storing key-value pairs with a distinction of Single Key and Multiple Values. See the original article here. Over a million developers have joined DZone. Let's be friends:. DZone 's Guide to. Sometimes you want to store multiple values for the same hash key. The following code examples show you three different ways to do this. Free Resource. Like 7. Join the DZone community and get the full member experience.
Join For Free. Scenario HashMap can be used to store key-value pairs. ArrayList; import java. HashMap; import java. List; import java. Set; import com. ArrayListMultimap; import com. Set; import org. MultiMap; import org. Output The output for all the above three scenarios will be the same as the one below:.
It sounds like you're looking for a multimap. Guava has various Multimap implementations, usually created via the Multimaps class. I would suggest that using that implementation is likely to be simpler than rolling your own, working out what the API should look like, carefully checking for an existing list when adding a value etc.
If your situation has a particular aversion to third party libraries it may be worth doing that, but otherwise Guava is a fabulous library which will probably help you with other code too :.Return Multiple Match Results in Excel (2 methods)
This is what i found in a similar question's answer. A standard Java HashMap cannot store multiple values per key, any new entry you add will overwrite the previous one.
Thinking about a Map with 2 keys immediately compelled me to use a user-defined key, and that would probably be a Class. Following is the key Class:. This way each value for the key should have a unique identifier. Also gives O 1 for fetches,if keys are known. Write a new class that holds all the values that you need and use the new class's object as the value in your HashMap. Learn more. Asked 8 years, 4 months ago. Active 1 year, 5 months ago.
Viewed k times. How I can get the third value for the first key in this map? Is this possible? Yu Hao k 23 23 gold badges silver badges bronze badges. Sunscreen Sunscreen 3, 7 7 gold badges 29 29 silver badges 39 39 bronze badges.
I can get the first value for a key by using the member function of HashMap::get though the third one? I cannot find any code unfortunately. You cannot find your own code? That's what he is talking about. Sounds like you might be a little confused about the difference between keys and hashed keys.Posted by: admin November 15, Leave a comment.
Please do help me, also by telling if there is no way any other way to implement the storage of three values with one as the key? The disadvantage to this approach is that you have to write a lot of boiler-plate code for all of these very simple container classes.
Subscribe to RSS
No, not just as a HashMap. Take a look at the All Known Implementing Classes at the top of the page for specialized implementations. Take a look at Multimap from the guava-libraries and its implementation — HashMultimap. A collection similar to a Map, but which may associate multiple values with a single key. If you call put K, V twice, with the same key but different values, the multimap contains mappings from the key to both values.
This way, I can store multiple values of different types associated with a key. You have to take care by maintaining proper order of inserting and retrieving from Object. Example: Consider, we want to store Student information. Key is id, while we would like to store name, address and email associated to the student. Note that to ensure consistency in case multiple threads access this data structure, ConcurrentHashMap and CopyOnWriteArrayList for instance need to be used.
Yes and no. The solution is to build a Wrapper clas for your values that contains the 2 3, or more values that correspond to your key. If you use Spring Framework. There is: org. This is very simple and effective. If you want values of diferent classes instead, you can do the following:. I prefer the following to store any number of variables without having to create a separate class.
I am so used to just doing this with a Data Dictionary in Objective C. It was harder to get a similar result in Java for Android. I ended up creating a custom class, and then just doing a hashmap of my custom class.
The dark mode beta is finally here. Change your preferences any time. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Is it possible to have multiple values for the same key in a hash table? If not, can you suggest any such class or interface which could be used? Note that Multimap is not an exact equivalent of the home-baked solution; Hashtable synchronizes all its methods, while Multimap makes no such guarantee. This means that using a Multimap may cause you problems if you are using it on multiple threads.
HashMap – Single Key and Multiple Values Example
If your map is used only on one thread, it will make no difference and you should have been using HashMap instead of Hashtable anyway. In Java, the Hashtable class accepts a single value for a single key. The following is an example of an attempt to associate multiple values to a single key:.
In an attempt to include multiple values "World""Mom" to a single key "Hello"we end up with the following result for printing the entries in the Hashtable :. This shows that one cannot have multiple values associate with a single key in a Hashtable. What is really needed here is a multimapwhich allows an association of multiple values to a single key. One implementation of the multimap is Multimap from Google Collections :. This is similar to the example above which used Hashtablebut the behavior is quite different -- a Multimap allows the association of multiple values to a single key.
The result of executing the above code is as follows:. As can be seen, for the "Hello" key, the values of "Mom" and "World" associated with it. Unlike Hashtableit does not discard one of the values and replace it with another.
The Multimap is able to hold on to multiple values for each key. Are the multiple values related? If yes, then it's probably better that you create a data structure to hold them. If no, then perhaps it's more appropriate to use separate maps. Are you keeping them together so that you can iterate them based on the key? You might want to look for an alternative indexing data structure, like a SkipList. As others pointed out, no. Instead, consider using a Multimap which can map many values for the same key.Welcome to the devtech blog.
Read more about devtech and Eli Kleinman. Email Me : Use the Contact Form to get in touch with me, comments, questions or suggestions. You can also simply say hello!. Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information. Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies.
It is mandatory to procure user consent prior to running these cookies on your website. No Ratings Yet. ArrayList; import java. HashMap; import java. List; import java. ArrayList. HashMap. List. Map. Set; import com. ArrayListMultimap; import com. Set. ArrayListMultimap. Multimap. Set; import org.
MultiMap; import org.