Explain how to convert a list to a map using Streams in Java 8.

Converting a list to a map in Java 8 uses Stream.collect(Collectors.toMap()), where you supply a key-mapping function and a value-mapping function to derive each map entry from a list element.

Key Points: • Collectors.toMap(keyMapper, valueMapper) builds a Map from stream elements based on the supplied functions. • If two elements can produce the same key, a merge function must be supplied as a third argument to avoid an IllegalStateException. • An optional fourth argument lets you specify the map implementation, e.g. LinkedHashMap::new to preserve order. • The value mapper can be Function.identity() when you want the object itself as the value. • This approach is more concise than manually looping and calling map.put() for each element.

Example: Given a list of Employee objects, employees.stream().collect(Collectors.toMap(Employee::getId, Function.identity())) builds a Map<Integer, Employee> keyed by employee ID.

Code Example:

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

Map<String, Integer> nameLengths = names.stream()
        .collect(Collectors.toMap(n -> n, String::length));

System.out.println(nameLengths); // {Alice=5, Bob=3, Charlie=7}

Interview Tip: A concise interview answer is:

"I stream the list and call collect(Collectors.toMap(keyMapper, valueMapper)), where the key mapper and value mapper are functions derived from each element. If duplicate keys are possible, I supply a third merge-function argument to Collectors.toMap() to resolve the collision instead of letting it throw an exception."