- Print out all keys and values from a Map in Java
- Java Print HashMap Example
- How to print HashMap in Java?
- How to print all keys and values of HashMap using entrySet?
- Java 8 and above
- How to print all the keys of HashMap?
- How to print all the values of the HashMap?
- How to print HashMap containing custom class object as keys or values?
- How to print Map in Java 10 — Printing HashMap In Java 10
- Print all keys and values in HashMap using forEach + lambda expression
- Output
- Print all keys and values in HashMap using Collection.iterator() & Iterator.forEachRemaining()
- Output
- Print all keys and values in HashMap using Collection.stream() & Stream.forEach()
- Output
- Print all keys and values in HashMap using Stream.of() & Stream.forEach()
- Output
- Print all keys and values in HashMap using Iterator
- Output
- Print HashMap in Java
- Print HashMap using foreach method with keyset()
- Print HashMap using Consumer with entrySet()
- Print HashMap using Arrays’s asList() method
- Print HashMap using Collections’s singletonList()
- Print HashMap using getkey() and getValue with entrySet()
- Print HashMap using BiConsumer
Print out all keys and values from a Map in Java
This post will discuss various methods to print out all keys and values from a map in Java.
Related Posts:
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:
Java Print HashMap Example
This example shows how to print HashMap in Java. The example also shows how to print all keys, all values, and all key-value pairs of HashMap using different ways.
How to print HashMap in Java?
The AbstractMap class, the parent class of the HashMap class, has overridden the toString method which returns a string representation of the map. All key-value pairs are enclosed in < and >and separated by a comma (,). The iterator of the entry set returns the order of the key-value pairs.
How to print all keys and values of HashMap using entrySet?
If you do not want the default formatting done by the toString method, you can get the entry set from the HashMap and print all key-value pairs one by one using the for loop as given below.
Java 8 and above
If you are using Java version 8 and above, you can use the below given code to print all keys and values of HashMap.
How to print all the keys of HashMap?
The keySet method of the HashMap class returns a Set view containing all the keys of the HashMap.
You can also use the System.out.println statement instead of using the for loop if you do not want to change the output format.
How to print all the values of the HashMap?
The values method of the HashMap returns a Collection view containing all the values contained in the HashMap.
You can also use System.out.println statement instead of using the for loop if you do not want to change the output format.
How to print HashMap containing custom class object as keys or values?
In all of the above examples, we printed Integer and String objects using the System.out.println statement. They were printed fine because both of these classes have overridden the toString method. Let’s try to print HashMap containing custom class objects.
We have put objects of Emp class as values in the HashMap in below given example.
As you can see from the output, the keys were printed fine but the values were not. It is because our Emp class has not overridden the toString method so it inherited the method from the Object class.
The toString method of the Object class returns the class name of the object, followed by @, followed by the hexadecimal hash code of the object. The format is not readable and hence it is suggested for all the subclasses to override the toString method to produce informative text.
Let’s override the toString method in the Emp class and try again.
How to print Map in Java 10 — Printing HashMap In Java 10
Print all keys and values in HashMap using forEach + lambda expression
package com.jackrutorial; import java.util.HashMap; public class PrintingHashmapExample1 < public static void main (String[] args) < var map = new HashMap<>(); map.put(1, "Java"); map.put(2, "Spring MVC"); map.put(3, "AngularJS"); //Using forEach + lambda expression System.out.println("Using forEach + lambda expression"); map.forEach((k,v) -> System.out.println(k + " - " + v)); //Using for each loop System.out.println("Using for each loop"); for (var key : map.keySet()) < System.out.println("key: " + key); >for (var value : map.values()) < System.out.println("value: " + value); >> >
Output
Using forEach + lambda expression 1 - Java 2 - Spring MVC 3 - AngularJS Using for each loop key: 1 key: 2 key: 3 value: Java value: Spring MVC value: AngularJS
Print all keys and values in HashMap using Collection.iterator() & Iterator.forEachRemaining()
package com.jackrutorial; import java.util.HashMap; public class PrintingHashmapExample2 < public static void main (String[] args) < var map = new HashMap<>(); map.put(1, "Java"); map.put(2, "Spring MVC"); map.put(3, "AngularJS"); //Using Collection.iterator() & Iterator.forEachRemaining() System.out.println("Using Collection.iterator() & Iterator.forEachRemaining()"); map.keySet().iterator().forEachRemaining(k -> < System.out.println("Key: " + k); >); map.values().iterator().forEachRemaining(v -> < System.out.println("Value: " + v); >); > >
Output
Using Collection.iterator() & Iterator.forEachRemaining() Key: 1 Key: 2 Key: 3 Value: Java Value: Spring MVC Value: AngularJS
Print all keys and values in HashMap using Collection.stream() & Stream.forEach()
package com.jackrutorial; import java.util.HashMap; public class PrintingHashmapExample3 < public static void main(String[] args) < var map = new HashMap<>(); map.put(1, "Java"); map.put(2, "Spring MVC"); map.put(3, "AngularJS"); // Using Collection.stream() & Stream.forEach() System.out.println("Using Collection.stream() & Stream.forEach()"); map.keySet().stream().forEach(k -> < System.out.println("Key: " + k); >); map.values().stream().forEach(k -> < System.out.println("Key: " + k); >); > >
Output
Using Collection.stream() & Stream.forEach() Key: 1 Key: 2 Key: 3 Key: Java Key: Spring MVC Key: AngularJS
Print all keys and values in HashMap using Stream.of() & Stream.forEach()
package com.jackrutorial; import java.util.HashMap; import java.util.stream.Stream; public class PrintingHashmapExample4 < public static void main(String[] args) < var map = new HashMap<>(); map.put(1, "Java"); map.put(2, "Spring MVC"); map.put(3, "AngularJS"); // Using Stream.of() & Stream.forEach() System.out.println("Using Stream.of() & Stream.forEach()"); Stream.of(map.keySet().toString()).forEach(k -> < System.out.println("Key: " + k); >); Stream.of(map.values().toString()).forEach(v -> < System.out.println("Value: " + v); >); > >
Output
Using Stream.of() & Stream.forEach() Key: [1, 2, 3] Value: [Java, Spring MVC, AngularJS]
Print all keys and values in HashMap using Iterator
package com.jackrutorial; import java.util.HashMap; public class PrintingHashmapExample5 < public static void main(String[] args) < var map = new HashMap<>(); map.put(1, "Java"); map.put(2, "Spring MVC"); map.put(3, "AngularJS"); // Using Iterator System.out.println("Using Iterator"); var keyItr = map.keySet().iterator(); while (keyItr.hasNext()) < System.out.println("Key: " + keyItr.next()); >var vItr = map.values().iterator(); while (vItr.hasNext()) < System.out.println("Value: " + vItr.next()); >> >
Output
Using Iterator Key: 1 Key: 2 Key: 3 Value: Java Value: Spring MVC Value: AngularJS
Print HashMap in Java
This is the most basic and easiest method to print out HashMap in java. Pass the HashMap reference to the System.out.println, and the HashMap will output the key-value of the elements enclosed in curly brackets.
We will use a HashMap constructor and a pass Map of elements to the constructor, which provides an easier way to initialize a HashMap with values using the Map.of() method.
A Map is an interface that forms the basis for all map implementations, including a HashMap. The Map.of() method returns an unmodifiable map containing the number of elements you create.
If there are any duplicate keys, the method throws IllegalArgumentException and a NullPointerException if any key or value is null .
Print HashMap using foreach method with keyset()
The HashMap get(Object key) is a method that returns the value that belongs to a particular key.
To get the key for every value in the HashMap, we use a for-loop with the keySet() method.
The key set method returns a set of unique keys, and we pass the keys to the get method to retrieve each value.
Print HashMap using Consumer with entrySet()
To use Consumer functional interface, you have to use the entrySet() method, which returns a Set containing the same type of key-value elements.
Since the Set is a Collection class that implements Iterable , use the forEach() method to print out the elements of the HashMap.
The forEach() is a method from the Iterable class, and it accepts only a Consumer as the parameter.
The for-each method iterates through the elements in the HashMap until they are exhausted as it prints them out using System.out.println.
Print HashMap using Arrays’s asList() method
To print out the elements of a HashMap using this class, pass the HashMap reference to the asList() method of the Arrays class.
This method will print out a list of elements in the HashMap as an Array.
When the reference of the array is is null , it throws a NullpointerException except where noted.
Print HashMap using Collections’s singletonList()
The singletonList() is a static method from the Collections class hence no instantiation is required to use the method.
singletonList() returns an immutable list which is simply a list that can not be modified by either adding or removing elements from it once it has been created.
When you try to add or remove elements from the singleton list it throws an UnsupportedOperationException indicating that it is not supported in the list.
The singletonList method is generic meaning that it can handle any data type and, in our case just pass the HashMap reference and it will automatically infer the type.
Print HashMap using getkey() and getValue with entrySet()
To use the getKey() and getValue() methods, we use the entrySet() method which returns a Set of Map entries Map.Entry .
The map entry contains the key-value elements in the HashMap, and the elements are only available during the iteration period.
Since Set is a Collection the only way to reference the Map entry is by using an iterator inherited from the Iterable class.
A for loop will iterate through the elements in the Set of Map entries and print out the key for each value using the get key method and the value using the get value method.
Print HashMap using BiConsumer
BiConsumer is a Functional Interface that represents an operation that accepts two arguments and returns no value.
The BiConsumer functional interface is a parameter of the forEach() method. The for-each method is inherited by the HashMap from the Map interface.
The type declared in the HashMap is the only type of value that will be accepted by the BiConsumer .
The functional interface will use the accept() method behind the scenes to receive the key and value parameters from the HashMap.
The action of our consumer will be printing out the elements in the HashMap. Note that if the action is null or an entry is removed during iteration, the for-each method will throw a NullPointerException and CurrentModificationException , respectively.