1. Introduction
In Java, a Stream is a sequence of elements supporting sequential and parallel aggregate operations, while a Map is a collection of key-value pairs where keys are unique. Converting a Stream to a Map can be useful when we want to perform lookups, or we want to group our data by a certain attribute.
2. Program Steps
1. Import the necessary libraries.
2. Create a Stream of elements.
3. Convert the Stream to a Map using the collect method and Collectors.toMap().
4. Display the elements of the Map.
3. Code Program
// Step 1: Import the necessary libraries
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamToMapExample {
public static void main(String[] args) {
// Step 2: Create a Stream of elements
Stream<String> animalStream = Stream.of("Cat", "Dog", "Elephant");
// Step 3: Convert the Stream to a Map
Map<Integer, String> animalMap = animalStream.collect(Collectors.toMap(String::length, animal -> animal));
// Step 4: Display the elements of the Map
animalMap.forEach((key, value) -> System.out.println(key + ": " + value));
}
}
Output:
3: Dog 4: Cat 8: Elephant
4. Step By Step Explanation
Step 1: The necessary libraries are imported, including those for handling maps, streams, and collectors.
Step 2: A Stream of strings representing animal names is created using the Stream.of method.
Step 3: The Stream is converted to a Map using the collect method along with Collectors.toMap(). The key for each element in the Map is determined by the length of the animal name, and the value is the animal name itself. This results in a Map object, animalMap, where the keys are the length of animal names and the values are the animal names.
Step 4: Each key-value pair of the Map is printed to the console using the forEach method. The output demonstrates the Map structure with length of the animal name as the key and the animal name as the value.