0

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.

4
  • 5
    There's no need for that last line. This is sufficient: mainMap.get(1).put("abc", "abc+xyz"); (assuming that the 1 key is guaranteed to have a value). Commented Dec 24, 2019 at 9:57
  • you need not to put back map mainMap.put(1, map); as it's already there, you are only working on a reference of same Commented Dec 24, 2019 at 9:59
  • @RobbyCornelissen yes, its working fine. Thanks Commented Dec 24, 2019 at 10:04
  • If map doesn't contains key in that case i need to create new entry in mainMap. Commented Dec 24, 2019 at 10:10

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

i am not able to apply **put** directly on the result returned from computeIfAbsent(...).
@SagarGangwal Make sure that you initialize the main map properly. That is, Map<Intege,Map<String,String>> mainMap=new HashMap<>() - that <> is very important.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.