Sagar Gangwal
Sagar Gangwal

Reputation: 7980

Update value of Map of Map

I am using Java8 and I have one map

Map<Intege,Map<String,String>> mainMap=new HashMap()

currently i am updating value of inner map as below

Map map = mainMap.get(1);
map.put("abc", "abc+xyz");
mainMap.put(1, map);

Could anyone help me with Java8 or any other approach.

Upvotes: 0

Views: 332

Answers (1)

RealSkeptic
RealSkeptic

Reputation: 34638

First, you must avoid using raw types.

You have to initialize your main map properly using the diamond operator.

Map<Integer,Map<String,String>> mainMap=new HashMap<>()

That <> is very important.

Also, do not define map as just Map. It has to be defined as

Map<String,String> map = mainMap.get(1);

Now to the question itself. In similar situations, the issue is normally what happens when you haven't had a value for some key in the top map. You'd have to do something like this:

map = mainMap.get(1);
if ( map == null ) {
   map = new HashMap<>();
   mainMap.put(1, map);
}
map.put("some key", "some value");

If you didn't have the if clause, you'd run into a NullPointerException when you use map.put(...) if the main key didn't exist previously in the map.

Since Java 8, a few default methods were added to the Map interface, such that you can save up that boilerplate. The new idiom would be:

mainMap.computeIfAbsent(1, k->new HashMap<>()).put("some key", "some value");

If the map for 1 existed, it will be returned from computeIfAbsent. If it didn't exist, it will be created and placed in mainMap, and also returned. So you can use put directly on the result returned from computeIfAbsent(...).

Of course, this has to be done with properly defined and initialized map types - again, don't use raw types.

Upvotes: 3

Related Questions