Java HashMap.values()

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.

The syntax of values() function is

</>
Copy
values()

Returns

The function returns Collection of values.

Examples

1. values() basic example

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

</>
Copy
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]

2. values() – When HashMap is null

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

</>
Copy
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.