Convert Map to a Stream in Java
This post will discuss how to convert the map to a stream in Java.
1. Converting Map<K,V> to Stream<Map.Entry<K,V>>
We know that Map.entrySet() returns a set view of the mappings contained in this map. In Java 8, we can easily get a stream of key-value pairs, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; class Main { // Generic method to convert `Map<K, V>` to a stream of `<Map.Entry<K, V>` private static <K, V> Stream<Map.Entry<K, V>> mapToStream (Map<K, V> map) { return map.entrySet().stream(); } // Program to convert map to a stream public static void main(String[] args) { Map<String, Integer> asciiMap = new HashMap<>(); asciiMap.put("A", 65); asciiMap.put("B", 66); asciiMap.put("C", 67); Stream<Map.Entry<String, Integer>> stream = mapToStream(asciiMap); System.out.println(Arrays.toString(stream.toArray())); } } |
Output:
[A=65, B=66, C=67]
2. Converting Map<K,V> to Stream<K>
We can get a stream of keys of the map using Map.keySet() in Java 8 and above:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; class Main { // Generic method to convert `Map<K, V>` to a `Stream<K>` private static <K, V> Stream<K> mapToStream (Map<K, V> map) { return map.keySet().stream(); } // Program to convert map to a stream public static void main(String[] args) { Map<String, Integer> asciiMap = new HashMap<>(); asciiMap.put("A", 65); asciiMap.put("B", 66); asciiMap.put("C", 67); Stream<String> stream = mapToStream(asciiMap); System.out.println(Arrays.toString(stream.toArray())); } } |
Output:
[A, B, C]
3. Converting Map<K,V> to Stream<V>
We can get a stream of values of the map using Map.values() in Java 8 and above:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; class Main { // Generic method to convert `Map<K, V>` to a stream<V> private static <K, V> Stream<V> mapToStream (Map<K, V> map) { return map.values().stream(); } // Program to convert map to a stream public static void main(String[] args) { Map<String, Integer> asciiMap = new HashMap<>(); asciiMap.put("A", 65); asciiMap.put("B", 66); asciiMap.put("C", 67); Stream<Integer> stream = mapToStream(asciiMap); System.out.println(Arrays.toString(stream.toArray())); } } |
Output:
[65, 66, 67]
That’s all about converting Map to a Stream in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)