Is it possible for us to implement a HashMap with one key and two values. Just as HashMap?
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?
Is it possible for us to implement a HashMap with one key and two values. Just as HashMap?
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?
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.
We can create a class to have multiple keys or values and the object of this class can be used as a parameter in map. You can refer to https://stackoverflow.com/a/44181931/8065321
No, not just as a
HashMap
. You'd basically need aHashMap
from a key to a collection of values.If you're happy to use external libraries, Guava has exactly this concept in
Multimap
with implementations such asArrayListMultimap
andHashMultimap
.You could:
Map<KeyType, List<ValueType>>
.Map<KeyType, WrapperType>
.Map<KeyType, Tuple<Value1Type, Value2Type>>
.Examples
1. Map with list as the value
The disadvantage with this approach is that the list is not bound to exactly two values.
2. Using wrapper class
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.
3. Using a tuple
This is the best solution in my opinion.
4. Multiple maps
The disadvantage of this solution is that it's not obvious that the two maps are related, a programmatic error could see the two maps get out of sync.
Just for the record, the pure JDK8 solution would be to use
Map::compute
method:Such as
with output:
Note that to ensure consistency in case multiple threads access this data structure,
ConcurrentHashMap
andCopyOnWriteArrayList
for instance need to be used.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.