Press "Enter" to skip to content

HashMap put() Method in Java

The put(key, value) method of HashMap inserts the key-value pair into the map. If the specified key is already available then it replaces the old value with the new value for that key.
put method returns the previous value associated with the specified key if there was mapping for the specified key else it returns null.

Syntax

Object put(K key, V value)

Parameters

key - key for the entry,
value - value to be associated with the key
Freshers Placement

Return type

previous value if the speified key exists in the map else returns null.

Program 1

import java.util.HashMap;
import java.util.Map;

public class HashMapPutExample {

	public static void main(String[] args) {

		Map<Integer, String> map = new HashMap<>();
		map.put(101, "John");
		map.put(102, "Adam");
		map.put(103, "Ricky");

		System.out.println("Returns null for new pair: " + map.put(104, "Chris"));
		System.out.println("Returns previous value for existing key: " + map.put(102, "Shaun"));
		System.out.println("Map elements: " + map);
	}
}

Output

Returns null for new pair: null
Returns previous value for existing key: Adam
Map elements: {101=John, 102=Shaun, 103=Ricky, 104=Chris}

Program 2

import java.util.HashMap;
import java.util.Map;

class Employee {
	private int employeeId;
	private String employeeName;

	public Employee() {
	}

	public Employee(int employeeId, String employeeName) {
		super();
		this.employeeId = employeeId;
		this.employeeName = employeeName;
	}

	@Override
	public String toString() {
		return "Employee [employeeId=" + employeeId + ", employeeName=" + employeeName + "]";
	}
}

public class HashMapPutExample {

	public static void main(String[] args) {

		Map<String, Employee> map = new HashMap<>();
		map.put("IT", new Employee(101, "John"));
		map.put("Electronics", new Employee(102, "Chris"));
		map.put("Computer", new Employee(103, "Ricky"));

		for (Map.Entry<String, Employee> employee : map.entrySet()) {
			System.out.println("Department: " + employee.getKey() + " Employee details: " + employee.getValue());
		}
	}
}

Output

Department: Electronics Employee details: Employee [employeeId=102, employeeName=Chris]
Department: Computer Employee details: Employee [employeeId=103, employeeName=Ricky]
Department: IT Employee details: Employee [employeeId=101, employeeName=John]

Comments are closed.