To add elements to a HashMap
in Java, you can use the put
method of the HashMap
class.
The put
method takes two arguments: the key and the value, and it adds a new element to the HashMap
with the specified key and value, or it updates the value of an existing element with the same key.
Here is an example of how you can add elements to a HashMap
in Java:
import java.util.HashMap; public class Main { public static void main(String[] args) { // Create a HashMap HashMap<String, Integer> map = new HashMap<>(); // Add some elements to the HashMap map.put("Apple", 10); map.put("Banana", 20); map.put("Orange", 30); // Print the HashMap System.out.println(map); // Output: {Apple=10, Banana=20, Orange=30} } }
In this example, the map
variable is a HashMap
that maps strings (the keys) to integers (the values).
The put
method is used to add three elements to the HashMap
: "Apple" with a value of 10, "Banana" with a value of 20, and "Orange" with a value of 30.
Then, the map
variable is printed, and it contains the three elements that were added to the HashMap
.
It is important to note that the put
method returns the previous value of the element with the same key, or null
if the key is not present in the HashMap
.
Therefore, you can use the return value of the put
method to determine whether a new element was added to the HashMap
or an existing element was updated.
For example:
Integer previous = map.put("Apple", 15); if (previous == null) { System.out.println("Added a new element to the HashMap"); } else { System.out.println("Updated the value of an existing element in the HashMap"); }
In this example, the put
method updates the value of the element with the key "Apple" to 15, and it returns the previous value of the element, which is 10.
Therefore, the if
statement prints the message "Updated the value of an existing element in the HashMap".
It is also possible to use the putIfAbsent
method.