Java – How to get all values of a HashMap ?

In this article, we will discuss how to get all values of a HashMap or implementation classes of Map interface like LinkedHashMap or TreeMap

1. Map implementation classes:

  • HashMap –> retrieves values, in random-order of keys
  • LinkedHashMap –> retrieves values, as per insertion-order of keys
  • TreeMap –> retrieves values, as per some sorting-order of keys

2. To get all values of HashMap :

  • use values() method of Map interface
  • which returns Collection of values

Syntax:

Collection<String> values = hashMap.values();

GetAllValuesOfHashMap.java

package in.bench.resources.java.map;

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

public class GetAllValuesOfHashMap {

	public static void main(String[] args) {

		// creating HashMap object of type <String, String>
		HashMap<String, String> hm = new HashMap<String, String>();

		// adding key-value pairs to HashMap object
		hm.put("Google", "Sundar Pichai");
		hm.put("Facebook", "Mark Zuckerberg");
		hm.put("LinkedIn", "Reid Hoffman");
		hm.put("Apple", "Steve Jobs");
		hm.put("Microsoft", "Bill Gates");

		System.out.println("all Key-Value pairs:\n\n" + hm + "\n\n");

		System.out.println("List of all values: \n");

		// Iterating value using values()
		Collection<String> founders = hm.values();
		for(String founder : founders) {
			System.out.println(founder);
		}
	}
}

Output:

all Key-Value pairs:

{Google=Sundar Pichai, LinkedIn=Reid Hoffman, Apple=Steve Jobs, Microsoft=Bill Gates, 
Facebook=Mark Zuckerberg}


List of all values: 

Sundar Pichai
Reid Hoffman
Steve Jobs
Bill Gates
Mark Zuckerberg

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - How to get all Entries or Key-Value pairs of HashMap ?
Java - How to get all keys of a HashMap ?