Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put/get values into/from Nested HashMap

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!

like image 633
user1927105 Avatar asked Jan 29 '13 12:01

user1927105


People also ask

How do you return a value from a HashMap?

get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.

How do I retrieve an element from a Map?

The get() method returns a specified element from a Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map object.


2 Answers

Map<Float, Map<Float, Integer>> map = new HashMap<>();

map.put(.0F, new HashMap(){{put(.0F,0);}});
map.put(.1F, new HashMap(){{put(.1F,1);}});

map.get(.0F).get(.0F);
like image 138
isvforall Avatar answered Sep 28 '22 01:09

isvforall


You have to get() the nested map out of the outer map and call can call put() and get() on it

float x = 1.0F;
HashMap<Float, Integer> innerMap = hashX.get(x);
if (innerMap == null) {
    hashX.put(x, innerMap = new HashMap<>()); // Java version >= 1.7
}
innerMap.put(2.0F, 5);
like image 36
jlordo Avatar answered Sep 28 '22 00:09

jlordo