How to convert List to Map?
To convert a List
to a Map
in Java, you can use the stream()
method and the collect()
method along with a Collectors.toMap()
call. Here's an example of how to do this:
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Example {
public static void main(String[] args) {
List<Person> list = // create your list here
Map<String, Person> map = list.stream().collect(Collectors.toMap(Person::getName, p -> p));
}
}
class Person {
private String name;
// other fields and methods go here
public String getName() {
return name;
}
}
This will create a Map
that maps the names of the Person
objects to the Person
objects themselves.
The toMap()
method takes two arguments: a function that returns the key for an element, and a function that returns the value for an element. In this example, the key is the name of the Person
object (returned by the getName()
method) and the value is the Person
object itself.
You can also specify an additional mergeFunction
argument if you want to specify how to handle cases where the map already contains a value for a given key. For example:
Map<String, Person> map = list.stream().collect(Collectors.toMap(Person::getName, p -> p, (p1, p2) -> p1));
This will create a map that keeps the first Person
object for each name and discards any subsequent ones.
Note that this approach assumes that the List
does not contain any duplicate keys. If the List
does contain duplicate keys, you will need to handle them appropriately (for example, by throwing an exception or by using a different mergeFunction
).