Sometimes the blog content will change. The first blog is the latest, and other blog addresses may not be synchronized. Check it carefully.
https://blog.zysicyj.top
Methods are available to convert List to Map using Java Stream Collectors.toMap()
. toMap()
The method accepts two parameters, the first parameter is a function used to extract the key of the Map, and the second parameter is a function used to extract the value of the Map. Here is an example:
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 35)
);
Map<String, Integer> ageByName = people.stream()
.collect(Collectors.toMap(Person::getName, Person::getAge));
System.out.println(ageByName);
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
In the above example, we have a Person
class that represents person information, including name and age. We List<Person>
convert one to one Map<String, Integer>
with name as key and age as value. Use Person::getName
as key extraction function, Person::getAge
as value extraction function. Finally, we print the results.
This article is published by mdnice multi-platform