Sobes.tech
Junior — Middle

Can the collect method be used to convert a Stream into a Map?

sobes.tech AI

Answer from AI

Yes, the collect method in Java's Stream API can be used to convert a stream into a map. This is done using the Collectors.toMap() collector, which takes functions for the key and value.

Example:

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

public class Example {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("apple", "banana", "cherry");

        Map<String, Integer> map = list.stream()
            .collect(Collectors.toMap(
                s -> s,          // key — the string itself
                s -> s.length()   // value — length of the string
            ));

        System.out.println(map); // {apple=5, banana=6, cherry=6}
    }
}

It is important that the keys are unique, otherwise an exception will be thrown. If keys can repeat, you need to use the version of toMap with a third parameter — a merge function.