How to put/get values into/from Nested HashMap
Solution 1
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);
Solution 2
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);
Solution 3
You can create a wrapper class with a method like this:
public class MyWrapper {
private Map<Float, Map<Float, Integer>> hashX;
// ...
public void doublePut(Float one, Float two, Integer value) {
if (hashX.get(one) == null) {
hashX.put(one, new HashMap<Float, Integer>());
}
hashX.get(one).put(two, value);
}
}
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
into ConcurrentHashMap
if the need arises.
Solution 4
You can do it like this:
HashMap<Float, Integer> h1 = new HashMap<Float, Integer>();
h1.put(1.0f,new Integer(1));
HashMap<Float, Integer> h2 = new HashMap<Float, Integer>();
h2.put(3.0f,new Integer(3));
hashX.put(1.0f, h1);
hashX.put(1.0f, h1);
user1927105
Updated on July 26, 2021Comments
-
user1927105 almost 3 years
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!
-
jlordo over 11 yearsWhy don't you save the reference to the new map, to avoid the following lookup operation, like you saw in my answer?
-
Adam Arold over 11 yearsAnd the infamous instance initializer block appears. :)
-
jlordo over 11 yearsThat's a
NullPointerException
, becausemap.get(0)
will returnnull
-
user1927105 over 11 years@isvforall thanks, is there anyway around using HashMap<>(), i'm using Android and I can't use level 1.7 as Android requires 5.0
-
Adam Arold over 11 yearsWell this looked somewhat a more idiomatic way to do it.
-
isvforall over 11 years@user1927105 Unfortunately, only
HashMap<Float, Map<Float, Integer>>();
-
Janac Meena almost 5 years@AdamArold why infamous?
-
Adam Arold almost 5 years@JanacMeena this is subjective, but most people I know don't like it (including me) because it makes the code harder to read and reason about.