Java 8: Convert List to Map
In Java 8, you can use the Collectors.toMap() method to convert a List into a Map. Here is a simple example code:
Assume there is a class Person:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// getters and setters
}
We currently have a List that we want to convert into a Map, with the key being the name and the value being the age.
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Person> personList = List.of(
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 35)
);
Map<String, Integer> personMap = personList.stream()
.collect(Collectors.toMap(Person::getName, Person::getAge));
System.out.println(personMap);
}
}
In the code above, we are using personList.stream().collect(Collectors.toMap(Person::getName, Person::getAge)) to convert a List into a Map
Please note that if there are duplicate keys in the List, an IllegalStateException exception will be thrown. You can use another overload of Collectors.toMap() method, specifying a merge function to handle duplicate keys.