Convert Stream to Map in Java

1. Introduction

Converting a Stream to a Map in Java is a powerful operation, especially when you need to transform a collection of objects into a key-value pair format for easy lookup and processing. The Java Stream API, introduced in Java 8, allows for expressive and efficient data processing operations. Using Collectors.toMap(), you can collect elements from a Stream into a Map based on transformation functions you define. This blog post will demonstrate how to convert a Stream into a Map, highlighting its usefulness in organizing data.

2. Program Steps

1. Create a Stream of custom objects or pairs that will serve as the source for the Map.

2. Use the collect method along with Collectors.toMap() to convert the Stream to a Map, specifying key and value extractors.

3. Display the resulting Map.

3. Code Program

import java.util.*;
import java.util.stream.*;
import java.util.stream.Collectors;

class Fruit {
    String name;
    int quantity;

    Fruit(String name, int quantity) {
        this.name = name;
        this.quantity = quantity;
    }

    public String getName() {
        return name;
    }

    public int getQuantity() {
        return quantity;
    }
}

public class StreamToMap {
    public static void main(String[] args) {
        // Step 1: Creating a Stream of custom objects
        Stream<Fruit> fruitStream = Stream.of(
            new Fruit("Apple", 10),
            new Fruit("Banana", 20),
            new Fruit("Cherry", 30)
        );

        // Step 2: Converting Stream to Map
        Map<String, Integer> fruitMap = fruitStream.collect(
            Collectors.toMap(
                Fruit::getName, // Key extractor
                Fruit::getQuantity // Value extractor
            )
        );

        // Step 3: Displaying the resulting Map
        System.out.println("Map from Stream: " + fruitMap);
    }
}

Output:

Map from Stream: {Apple=10, Banana=20, Cherry=30}

Explanation:

1. The program starts by defining a Fruit class with name and quantity fields, along with getters for these fields. This class represents the objects that will be transformed into Map entries.

2. A Stream<Fruit> is created using Stream.of(), containing several Fruit objects.

3. The Stream is then converted into a Map<String, Integer> using the collect method in conjunction with Collectors.toMap(). The key extractor function, Fruit::getName, specifies that the name field of each Fruit object should be used as the Map key. Similarly, the value extractor function, Fruit::getQuantity, specifies that the quantity field should be used as the Map value. This effectively transforms each Fruit object in the Stream into a key-value pair in the resulting Map.

4. Finally, the fruitMap is printed to the console, showing a Map where each fruit's name is associated with its quantity. This demonstrates how to use the Stream API and Collectors.toMap() to transform a collection of objects into a Map, facilitating easy data organization and retrieval.

Comments