To increase the value of an element in a HashMap
in Java by 1, you can use the get
and put
methods of the HashMap
class.
Here is an example of how to increase the value of an element in a HashMap
by 1:
HashMap<String, Integer> map = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); map.put("orange", 3); String key = "banana"; int value = map.get(key); value++; map.put(key, value);Source:ttual.wwwuri.com
In this example, the map
variable is a HashMap
object that maps strings to integers. The get
method retrieves the value of the element with the specified key, and the put
method updates the value of the element.
You can also use the merge
method of the HashMap
class to increase the value of an element by a specified amount.
For example:
map.merge(key, 1, Integer::sum);
In this example, the merge
method will add 1 to the value of the element with the key key
. If the element does not exist in the map, it will be added with a value of 1.
The merge
method takes three arguments: the key, the value to be added to the element, and a merge function. The merge function specifies how to combine the old and new values. In this case, the Integer::sum
method is used to add the old and new values together.
You can also use the compute
method of the HashMap
class to increase the value of an element by a specified amount.
For example:
map.compute(key, (k, v) -> v + 1);