2

Is there a built in implementation in java for hash map whose values are linked lists?

like, if I put:

 map.put(1, "A");
 map.put(1, "B");

then it automatically add A and B to the linked list. When I retrieve from the map, as:

 map.get(1)

I get back a list containing both of them?

kosa
66.7k15 gold badges134 silver badges170 bronze badges
asked Nov 2, 2012 at 19:36

3 Answers 3

4

Java does not have it but you can use MultiMap from Google Guava.

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.

The methods get(K), keySet(), keys(), values(), entries(), and asMap() return collections that are views of the multimap

This article Multimaps - Google Guava gives you complete idea about how to use it and also how to do it with HashMap using List as value.

answered Nov 2, 2012 at 19:38
2

Second put will overwrite first put. You will get B as response.

As per javadoc

If the map previously contained a mapping for the key, the old value is replaced

If you want to keep both entries, you need to use thrid party library google guava MultiMap

answered Nov 2, 2012 at 19:38
1

Nope, just build your own.

First you take a HashMap, if the key does not exist you put the linkedList in...

Simple...

answered Nov 2, 2012 at 19:39

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.