Java 8 - Convert Map to Stream

Introduction

In Java 8, the Stream API allows you to perform various operations on collections, including Map. You can easily convert a Map into a stream of its entries, keys, or values. This is useful when you want to apply functional operations like filtering, mapping, or reducing on Map data.

In this guide, we will learn how to convert a Map into a stream and demonstrate several operations that can be performed on the keys, values, or entries.

Solution Steps

  1. Define the Map: Create a Map with key-value pairs.
  2. Convert the Map to a Stream: Use entrySet().stream() for entries, keySet().stream() for keys, or values().stream() for values.
  3. Process the Stream: Apply operations such as filter(), map(), or collect().
  4. Collect or Display the Result: Collect the result back to a List or Set or print the processed elements.

Java Program

Example 1: Convert Map Entries to Stream

In this example, we convert the map's entries into a stream and process both keys and values.

import java.util.HashMap;
import java.util.Map;

public class MapToStreamExample {
    public static void main(String[] args) {
        // Step 1: Define a Map
        Map<String, Integer> employeeAges = new HashMap<>();
        employeeAges.put("Ravi", 30);
        employeeAges.put("Amit", 25);
        employeeAges.put("Pooja", 35);

        // Step 2: Convert the Map's entries to a Stream
        employeeAges.entrySet().stream()
                    // Step 3: Process the stream (Print key and value)
                    .forEach(entry -> System.out.println("Name: " + entry.getKey() + ", Age: " + entry.getValue()));
    }
}

Output

Name: Ravi, Age: 30
Name: Amit, Age: 25
Name: Pooja, Age: 35

Explanation

Step 1: Define the Map

We define a map where the key is the employee's name and the value is the employee's age:

Map<String, Integer> employeeAges = new HashMap<>();
employeeAges.put("Ravi", 30);
employeeAges.put("Amit", 25);
employeeAges.put("Pooja", 35);

Step 2: Convert the Map's Entries to a Stream

We use entrySet().stream() to convert the map's entries (both key and value) into a stream:

employeeAges.entrySet().stream();

Step 3: Process the Stream

We use forEach() to print each entry (key-value pair):

.forEach(entry -> System.out.println("Name: " + entry.getKey() + ", Age: " + entry.getValue()));

Example 2: Convert Map Keys to Stream

In this example, we convert only the keys of the map into a stream and process them.

import java.util.HashMap;
import java.util.Map;

public class MapKeysToStreamExample {
    public static void main(String[] args) {
        // Step 1: Define a Map
        Map<String, Integer> employeeAges = new HashMap<>();
        employeeAges.put("Ravi", 30);
        employeeAges.put("Amit", 25);
        employeeAges.put("Pooja", 35);

        // Step 2: Convert the Map's keys to a Stream
        employeeAges.keySet().stream()
                    // Step 3: Process the stream (Print each key)
                    .forEach(System.out::println);
    }
}

Output

Ravi
Amit
Pooja

Explanation

Step 1: Define the Map

We define the same map as in Example 1.

Step 2: Convert the Map's Keys to a Stream

We use keySet().stream() to convert the map's keys into a stream:

employeeAges.keySet().stream();

Step 3: Process the Stream

We use forEach() to print each key:

.forEach(System.out::println);

Example 3: Convert Map Values to Stream

In this example, we convert only the values of the map into a stream and process them.

import java.util.HashMap;
import java.util.Map;

public class MapValuesToStreamExample {
    public static void main(String[] args) {
        // Step 1: Define a Map
        Map<String, Integer> employeeAges = new HashMap<>();
        employeeAges.put("Ravi", 30);
        employeeAges.put("Amit", 25);
        employeeAges.put("Pooja", 35);

        // Step 2: Convert the Map's values to a Stream
        employeeAges.values().stream()
                    // Step 3: Process the stream (Print each value)
                    .forEach(System.out::println);
    }
}

Output

30
25
35

Explanation

Step 1: Define the Map

We define the same map as in Example 1.

Step 2: Convert the Map's Values to a Stream

We use values().stream() to convert the map's values into a stream:

employeeAges.values().stream();

Step 3: Process the Stream

We use forEach() to print each value:

.forEach(System.out::println);

Example 4: Filter Map Entries Based on Value

You can also filter the entries of a map based on certain criteria, such as filtering employees above a certain age.

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class FilterMapEntries {
    public static void main(String[] args) {
        // Step 1: Define a Map
        Map<String, Integer> employeeAges = new HashMap<>();
        employeeAges.put("Ravi", 30);
        employeeAges.put("Amit", 25);
        employeeAges.put("Pooja", 35);

        // Step 2: Convert the Map's entries to a Stream and filter based on value
        Map<String, Integer> filteredMap = employeeAges.entrySet().stream()
                                                       .filter(entry -> entry.getValue() > 30)  // Step 3: Filter employees above 30
                                                       .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        // Step 4: Display the filtered Map
        System.out.println(filteredMap);  // Output: {Pooja=35}
    }
}

Output

{Pooja=35}

Explanation

Step 1: Define the Map

We define the same map as in Example 1.

Step 2: Convert the Map's Entries to a Stream and Filter Based on Value

We convert the map's entries into a stream and use filter() to retain only entries where the value (age) is greater than 30:

.filter(entry -> entry.getValue() > 30);

Step 3: Collect the Filtered Entries

We use Collectors.toMap() to collect the filtered entries back into a map:

.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

Step 4: Display the Filtered Map

We print the resulting filtered map:

System.out.println(filteredMap);

Conclusion

In Java 8, converting a Map to a stream is straightforward using the entrySet().stream(), keySet().stream(), or values().stream() methods. Once converted, you can apply various stream operations like filtering, mapping, and collecting the result back into a map or list. This functional approach makes it easier to manipulate Map data in a more concise and readable manner.

Comments