Press "Enter" to skip to content

HashMap get() Method in Java

The get(K key) method of HashMap returns the value for the specified key. If the map does not contain an entry for the specified key then it returns null. It throws NullPointerException if the specified key is null and this map does not permit null keys.

Syntax

Object get(K key)

Parameter

The key to retrieve the value for
Freshers Placement

Return Type

It returns the value for the specified key

Program 1

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

public class HashMapGetExample {

	public static void main(String[] args) {

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

		System.out.println("Map elements: " + map);
		System.out.println("Get the value for key 102: " + map.get(102));
	}
}

Output

Map elements before clear: {101=John, 102=Adam, 103=Ricky, 104=Chris}
Map elements after clear: {}

Program 2

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

public class HashMapGetExample {

	public static void main(String[] args) {

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

		System.out.println("Map elements: " + map);
		System.out.println("Get the value for key 108: " + map.get(108));
	}
}

Output

Map elements: {101=John, 102=Adam, 103=Ricky, 104=Chris}
Get the value for key 108: null

Comments are closed.