I want to create a nested HashMap that will take two keys of type float and give out value of type Integer.
public static HashMap<Float, HashMap<Float, Integer>> hashX = new HashMap<Float,HashMap<Float, Integer>>();
Is there a simple method of putting/getting the values like an ordinary HashMap i.e.
hashX.put(key, value);
hashX.get(key);
or is it a more complicated method that must be used? I have searched around the web for a solution but am finding it tough to find a solution that applies to me. Any help would be appreciated!
You can do it like this:
You can create a wrapper class with a method like this:
Please note that you should use interfaces instead of concrete implementations when you declare your fields. For example it would make easier to refactor
HashMap
intoConcurrentHashMap
if the need arises.You don't need a nested Map for that. If you want to lookup using a composite key, it is better to declare your map to be as such. There isn't a good
Pair
class in JFK, but you ca useMap.Entry
, which is somewhat inconvenient to use but works:See https://stackoverflow.com/a/3110563/18573 for creating
Map.Entry
instancesYou have to
get()
the nested map out of the outer map and call can callput()
andget()
on it