Home > Back-end >  How to have one liner code for creating and updating map entries?
How to have one liner code for creating and updating map entries?

Time:12-09

In C , when using maps, one of the ways we can quickly create a new entry and update a map at the same time is by simply doing something like:

dict[key] =1;

This allows you to bypass checking to see if a particular key already exists, and then creating an if else statement for it.

I was wondering if there was something similar for Java, especially for a put command.

At present I am stuck using two separate put statements. Trying to use a put statement and combining an addition statement with the value parameter hasn't worked.

CodePudding user response:

Java Map has several related methods, depending on what you need. Probably the most generic method is merge. Your example would translate to:

dict.merge(key, 1, (oldValue, value) -> oldValue   value);

There are also a few simpler methods for other purposes, e.g. computeIfAbsent.

CodePudding user response:

Seems it is not possible in the Java world. In c when the key is not present in the map, the key, value pair gets added and its value is by default set to 0 [Default value in map], but in Java when the key is not found it returns null.

But it is possible to bypass the checking by setting the default return value to 0,

int key = 2;
HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
hm.put(key, hm.getOrDefault(key, 0)   1);

HashMap_doc

  • Related