Java HashMap.values() – Examples

In this tutorial, we will learn about the Java HashMap.values() function, and learn how to use this function to get all the values in this HashMap as a Collection, with the help of examples.

values()

HashMap.values() returns a values contained in this HashMap as a Collection.

Syntax

The syntax of values() function is

values()

Returns

The function returns Collection of values.

Example 1 – values()

In this example, we will initialize a HashMap hashMap with four mappings in it. To get all the values in this collection, call values() method on this HashMap.

Java Program

import java.util.Collection;
import java.util.HashMap;

public class Example{ 
	public static void main(String[] args) {
		HashMap<Integer, String> hashMap = new HashMap<>();
		hashMap.put(1, "A");
		hashMap.put(2, "B");
		hashMap.put(3, "C");
		hashMap.put(4, "D");
		System.out.println("HashMap  : " + hashMap);
		
		Collection<String> values = hashMap.values();
		System.out.println("Values   : " + values);
	}
}

Output

HashMap  : {1=A, 2=B, 3=C, 4=D}
Values   : [A, B, C, D]

Example 2 – values() – Null HashMap

In this example, we will initialize a HashMap hashMap with null value. values() method throws java.lang.NullPointerException when called on a null HashMap.

Java Program

import java.util.Collection;
import java.util.HashMap;

public class Example{ 
	public static void main(String[] args) {
		HashMap<Integer, String> hashMap = null;
		
		Collection<String> values = hashMap.values();
		System.out.println("Values   : " + values);
	}
}

Output

Exception in thread "main" java.lang.NullPointerException
	at Example.main(Example.java:8)

Conclusion

In this Java Tutorial, we have learnt the syntax of Java HashMap.values() function, and also learnt how to use this function with the help of examples.