Print out all keys and values from a Map in Java

In this post, we will discuss various methods to print out all keys and values from a Map in Java.


 
Related Post:

5 ways to Iterate Map in Java using entrySet()

5 ways to Iterate Map using keySet() in Java

 
We know that keySet() method returns a Set view of the keys contained in the map and values() method returns a Set view of the values contained in the map. So we can use keySet() to print all keys present in the Map and values() to print all values. There are several ways to do that –

 

1. Using Iterator

Map doesn’t have its own iterator since it don’t extend Collection Interface. Both keySet() and values() return Set and Set extends the Collection Interface, we can get an iterator.

 

2. For-each Loop

For-each loop is available to any object implementing Iterable Interface. As Set extends Iterable Interface, we can use for-each loop to loop through the keySet and values.

 

3. Java 8 – Iterator.forEachRemaining()

The Iterator Interface provides forEachRemaining() method that can print each element until all elements have been processed.

 

4. Java 8 – Stream.forEach()

We can use loop through the keySet and values by using Stream.forEach() method that can print each element of the stream.

 

5. Using toString()

For displaying all keys or values present in the map, we can simply print the string representation of keySet() and values() respectively.

 
Below is a simple Java program that print all keys of a Map using keySet() in Java –

Java

Download   Run Code

 
Similarly, below Java program print all values of a Map using values() in Java –

Java

Download   Run Code

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz