java.util.HashMap put(K key, V value)
Description :
On this document we will be showing a java example on how to use the put() method of HashMap Class. Basically this method is to add key value pair to the HashMap object. Please take note of the Generics before using the put method. From our discussion on HashMap we have discussed Generics. Lets do a recap on Generics by taking below declaration of HashMap:
HashMap<Integer,String> Studentmap = new HashMap<Integer,String>();
From the above code snippet, the key would be Integer while the value is String. As of Java 5, Generics is already around. This is to make sure that the object passed is restricted to the object type or its subclass that has been declared on the initialization of our map. If you are interested to learn more about this, please visit the official oracle documentation on Generics.
Getting back to the original topic, this method basically just to populate our HashMap objects with key value pair. So what if we have used a key that is already on the HashMap? Will it throw an exception or the value will be replaced with a new one? The old value will be replaced by a new one if the key is already on the HashMap object.
Important notes for put(K key, V value) method:
- specified by put in interface Map<K,V>
- overrides put in class AbstractMap<K,V>
Method Syntax :
public V put(K key, V value)
Parameter Input :
DataType | Parameter | Description |
---|---|---|
Object | key | key with which the specified value is to be associated |
Object | value | value to be associated with the specified key |
Method Returns :
The put method returns the previous value associated with key, or null if there was no mapping for key.
Compatibility Version :
Requires Java 1.2 and up
Exception :
N/A
Java Code Example :
This java example source code demonstrates the use of put() method of HashMap class. From the example below, basically we just ask the user input for the student id together with the student name. The id number is used as a key to access the value on the hashMap. Meanwhile the student name will correspond as the value to be stored on the HashMap. As you would have noticed we have a check in place if any replacement has been made to the existing value on the HashMap. In real life scenario you probably would be the doing the same as what we have done but would contains additional code to save the information on the database or maybe on a file. Though those functionality was not included on this basic example, we have already laid down the foundation on how to efficiently used a significant amount of methods available on HashMap.
package com.javatutorialhq.java.examples; import java.util.HashMap; import java.util.Scanner; /* * This example source code demonstrates the use of * put() method of HashMap class */ public class HashMapPutExample { public static void main(String[] args) throws InterruptedException { // declare the hashmap HashMap<Integer, String> mapStudent = new HashMap<>(); boolean loopAgain = true; Scanner scan = new Scanner(System.in); // loop while user not entering no do { // ask for user input for id number System.out.print("Enter ID number:"); Integer idNumber = Integer.parseInt(scan.nextLine()); // ask for user input which corresponds to student name System.out.print("Enter Name:"); String name = scan.nextLine(); // add the key value pair from user input to the hashmap String oldVal = mapStudent.put(idNumber, name); if (oldVal!=null) { System.out.println("Student Id Number:" + idNumber + " is " + oldVal + " and has been overwritten by " + name); } // ask user to check if another entry is required System.out.print("Enter another student (y/n)?"); String answer = scan.nextLine(); // condition to satisfy in order to loop again if (answer.equals("y") || answer.equals("Y")) { continue; } else { break; } } while (loopAgain); scan.close(); System.out.println("\n**********************************"); System.out.println("The following students are in database"); System.out.println(" ID Number "+ " Name"); for(int id:mapStudent.keySet()){ System.out.println(" "+id+" "+mapStudent.get(id)); } System.out.println("\n**********************************"); } }
Sample Output :
Running the above java example of the usage of HashMap put(Object key, Object Value) method will give the following output:
Similar Method :
The following are the list of method that you can go through for better understanding of the presented example
- HashMap put()
- HashMap keySet()
- Scanner nextLine()
Suggested Reading List :
References :