Java Hashmap put() Method
What is a Hashmap?
Hashmap was first introduced in Java 1.2.The Hashmap class is included in the java.util package.The data in a hashmap is stored in two parts: the key and the value, which can be accessed using an index of another type. A hashmap have unique keys , inserting a duplicate key will replace the data of the key. Hashmap class have many inbuilt method, one of those method is Java Hashmap put() Method.
To know more about Hashmap put() Method read the complete article
Java Hashmap put() Method
The hashmap put() method is used to insert insert key and the value mapped to that key in the hashmap.If you try to insert a duplicate key, it will replace the existing value with the new value . Below in this page you can find it’s syntax, return values, parameters with detailed examples.
Syntax :
hashmap.put(Object key , Object value);
Return values :
Null : when the new key and value is inserted. Return previous value which is mapped to the key when a duplicate key/value pair is inserted.
Hashmap put() Method Examples
Example 1 :
import java.util.*; public class Main { public static void main (String[]args) { // Creating an empty HashMap HashMap < Integer, String > hash_map_1 = new HashMap < Integer, String > (); // Initially hashmap is empty System.out.println ("Initially the hash_map_1 is empty : " + hash_map_1); // Mapping string values to int keys in a empty hashmap hash_map_1.put (10, "Java"); hash_map_1.put (20, "Hashmap"); hash_map_1.put (25, "put"); hash_map_1.put (30, "method"); //printing the hash_map_1 System.out.println ("final hashmap : " + hash_map_1); } }
Output :
Initially the hash_map_1 is empty : {} final hashmap : {20=Hashmap, 25=put, 10=Java, 30=method}
Example 2 :
import java.util.*; public class Main { public static void main (String[]args) { // Creating an empty HashMap HashMap < Integer, String > hash_map_1 = new HashMap < Integer, String > (); // Mapping string values to int keys in a empty hashmap hash_map_1.put (10, "Java"); hash_map_1.put (20, "Hashmap"); hash_map_1.put (25, "put"); hash_map_1.put (30, "method"); //inserting new pair of key and value System.out.println (hash_map_1.put(35,"New Value")); // insering a duplicate key and value pair System.out.println(hash_map_1.put(10,"Duplicate")); } }
Output :
null Java
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment