English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java HashMap put() method adds the specified item (key/Value mapping) inserted into the HashMap.
The syntax of the put() method is:
hashmap.put(K key, V value)
The HashMap put() method can take two parameters:
key - The specified value is mapped to the key
value - Value mapped using the specified key
If the key is already associated with any value, it returns the previously associated value
If the key is not associated with any value, it returns null
Note:If the key was previously associated with a null value, this method will also return null.
import java.util.HashMap; class Main { public static void main(String[] args) { // Creating HashMap HashMap<String, Integer> languages = new HashMap<>(); // Inserting items into HashMap languages.put("Java", 14; languages.put("Python", 3; languages.put("JavaScript", 1; // Display HashMap System.out.println("Programming languages: ") + languages); } }
Output Result
Programming languages: {Java=14, JavaScript=1, Python=3}
In the above example, we created a HashMap named languages. Here, the put() method willKey/Value mappingInsert into HashMap.
Note: Each item is inserted into the HashMap at a random position.
import java.util.HashMap; class Main { public static void main(String[] args) { // Creating HashMap HashMap<String, String> countries = new HashMap<>(); //Inserting items into HashMap countries.put("Washington", "America"); countries.put("Ottawa", "Canada"); countries.put("Kathmandu", "Nepal"); System.out.println("Countries: ") + countries); //Add elements with duplicate keys String value = countries.put("Washington", "USA"); System.out.println("Updated Countries: ") + countries); // Display the replacement value System.out.println("The replaced value: "); + value); } }
Output Result
Countries: {Kathmandu=Nepal, Ottawa=Canada, Washington=America} Updated Countries: {Kathmandu=Nepal, Ottawa=Canada, Washington=USA} The replaced value:
In the above example, we used the put() method to insert items into the hash table. Note this line,
countries.put("Washington", "USA");
In this case, the key 'Washington' already exists in the hash map. Therefore, the put() method replaces the previous value 'America' with the new value 'USA'.
NoteAs of now, we have only added one item. However, we can also useJava HashMap putAll()The method adds multiple items to the hash map.