Java Hashmap Add Elements

ht‮www//:spt‬.lautturi.com
Java Hashmap Add Elements

To add elements to a HashMap in Java, you can use the put method of the HashMap class.

Here is an example of how to add elements to a HashMap:

HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);

In this example, the map variable is a HashMap object that maps strings to integers. The put method adds a new element to the map or replaces an existing element with the same key.

The put method takes two arguments: the key and the value of the element. The key is used to look up the element in the map, and the value is the element itself.

You can also use the putAll method to add all the elements of another map to the current map:

HashMap<String, Integer> map2 = new HashMap<>();
map2.put("pear", 4);
map2.put("grape", 5);

map.putAll(map2);

In this example, the elements of map2 (i.e. "pear" and "grape") will be added to map. If an element with the same key as an element in map2 already exists in map, it will be replaced by the element from map2.

You can also use the putIfAbsent method to add an element to the map only if the key is not already present in the map.

For example:

map.putIfAbsent("apple", 6); // does nothing, because the key "apple" already exists in the map
map.putIfAbsent("mango", 7); // adds the element ("mango", 7) to the map

Note that the HashMap class is not thread-safe.

Created Time:2017-11-03 22:21:03  Author:lautturi