Sobes.tech
Junior — Middle

Have you used the collect() method to convert a Stream into a HashMap?

sobes.tech AI

Answer from AI

Yes, the collect() method in Java Stream API is often used to convert a stream of elements into collections, including HashMap.

To convert a Stream into a HashMap, you can use the collector Collectors.toMap(). For 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 — string
                s -> s.length()  // value — length of the string
            ));

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

If keys can repeat, you need to use the version of toMap with a merge function to avoid IllegalStateException.