How to get all keys of a HashMap

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

 

HashMap –> retrieves keys in random order
LinkedHashMap –> retrieves keys as per insertion order
TreeMap –> retrieves keys as per some sorting order

 

Solution:

  • use keyset() method of Map interface
  • which returns Set of Keys

 

Example: To get all keys of a HashMap using keySet () method

Syntax:

Set<String> set = hashMap.keySet();

 

GetAllKeysOfHashMap.java

package in.bench.resources.java.map;

import java.util.HashMap;
import java.util.Set;

public class GetAllKeysOfHashMap {

	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 keys using keySet(): \n");

		// Iterating keys using keySet()
		Set<String> companies = hm.keySet();
		for(String company : companies) {
			System.out.println(company);
		}
	}
}

Output:

all Key-Value pairs:

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


List of all keys using keySet(): 

Microsoft
Facebook
Apple
LinkedIn
Google

Note: We can also print values corresponding to keys retrieved using keySet() method

 

References:

https://docs.oracle.com/javase/tutorial/collections/intro/
https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
https://docs.oracle.com/javase/7/docs/api/java/util/Map.html
https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html
https://docs.oracle.com/javase/tutorial/collections/interfaces/map.html
https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
https://docs.oracle.com/javase/tutorial/collections/interfaces/set.html
https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
https://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html
https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html
https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html
https://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html
https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html

 

Happy Coding !!
Happy Learning !!

How to get all values of a HashMap
How to remove elements while iterating collection object