How to put/get values into/from Nested HashMap

2019-01-18 06:44发布

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!

5条回答
干净又极端
2楼-- · 2019-01-18 06:58

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);
查看更多
在下西门庆
3楼-- · 2019-01-18 07:00

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.

查看更多
Melony?
4楼-- · 2019-01-18 07:00

I want to create a nested HashMap that will take two keys of type float and give out value of type Integer.

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 use Map.Entry, which is somewhat inconvenient to use but works:

Map<Map<Float, Float>, Integer> map = new ....

See https://stackoverflow.com/a/3110563/18573 for creating Map.Entry instances

查看更多
5楼-- · 2019-01-18 07:11

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);
查看更多
劫难
6楼-- · 2019-01-18 07:15
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);
查看更多
登录 后发表回答