map.put(key, map.get(key) + 1);
should be fine. It will update the value for the existing mapping. Note that this uses auto-boxing. With the help of map.get(key) we get the value of corresponding key, then you can update with your requirement. Here I am updating to increment value by 1.
map.put(key, map.get(key) + 1);
should be fine. It will update the value for the existing mapping. Note that this uses auto-boxing. With the help of map.get(key) we get the value of corresponding key, then you can update with your requirement. Here I am updating to increment value by 1.
Java 8 way:
You can use computeIfPresent method and supply it a mapping function, which will be called to compute a new value based on existing one.
For example,
Map<String, Integer> words = new HashMap<>();
words.put("hello", 3);
words.put("world", 4);
words.computeIfPresent("hello", (k, v) -> v + 1);
System.out.println(words.get("hello"));
Alternatevely, you could use merge method, where 1 is the default value and function increments existing value by 1:
words.merge("hello", 1, Integer::sum);
In addition, there is a bunch of other useful methods, such as putIfAbsent, getOrDefault, forEach, etc.
int increment = 0;
if (tilesMap.containsKey('a'){
int value = tilesMap.get('a')
tilesMap.put('a', ++value);
increment ++;
}
after put, old value will be removed, new value will be assigned
That's working well if you have Map<Character, Integer>.
If you have Map<String, Integer>, use "a" instead of 'a'
take attention. Your could could not work because of using "char" literal but "String" in the key of map.
This code would compile and show "does not contain "a". So you could got illusion that you could not put something in to the map.
Map<String, Integer> tilesMap = new HashMap<String, Integer>();
Integer increment = 0;
tilesMap.put("a", increment);
if (tilesMap.containsKey('a')){
System.out.println("contain \"a\"");
int value = tilesMap.get('a');
// setting the increment value in 'a'
increment ++;
}else{
System.out.println("does not contain \"a\"");
}