This post will discuss various methods to print out all keys and values from a map in Java.

Related Posts:

Iterate Map in Java using the entrySet() method

Iterate Map in Java using keySet() method

 
We know that the 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 doesn’t extend the 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 the Iterable interface. As Set extends Iterable interface, we can use a for-each loop to loop through the keySet and values.

3. Java 8 – Iterator.forEachRemaining()

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

4. Java 8 – Stream.forEach()

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

5. Using toString()

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

 
Following is a simple Java program that prints all keys of a map using keySet() in Java:

Download  Run Code

 
Similarly, the following Java program print all values of a map using values() in Java:

Download  Run Code

That’s all about printing out all keys and values from a Map in Java.