W3docs

Java 8 List<V> into Map<K>

To convert a List<V> into a Map<K> in Java 8, you can use the toMap() method of the Collectors class from the java.util.stream package.

To convert a List<V> into a Map<K, V> in Java 8, you can use the toMap() method of the Collectors class from the java.util.stream package.

The toMap() method takes a function that extracts the key from an element and a function that extracts the value, and returns a Collector that accumulates elements into a Map. You can then use this collector with the collect() method of the Stream interface to create the map.

Here is an example of how to convert a List<V> into a Map<K, V> in Java 8:

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Person> list = Arrays.asList(
            new Person("Alice", 30),
            new Person("Bob", 25)
        );
        Map<String, Integer> map = list.stream()
            .collect(Collectors.toMap(
                Person::getName,
                Person::getAge,
                (existing, replacement) -> existing // Merge function for duplicate keys
            ));
    }

    static class Person {
        private final String name;
        private final int age;
        public Person(String name, int age) { this.name = name; this.age = age; }
        public String getName() { return name; }
        public int getAge() { return age; }
    }
}

This code creates a stream of the elements in the list using the stream() method and then collects them into a Map using the toMap() method and the collect() method.