Java Stream converts List to Map
Convert List to Map using Java Stream()
method.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 .*; import ; public class Main { public static void main(String[] args) { List<Person> people = ( new Person("Alice", 25), new Person("Bob", 30), new Person("Charlie", 35) ); Map<String, Integer> ageByName = () .collect((Person::getName, Person::getAge)); (ageByName); } } class Person { private String name; private int age; public Person(String name, int age) { = name; = age; } public String getName() { return name; } public int getAge() { return age; } }
In the example above, we have aPerson
Class represents personnel information, including name and age. We'll have oneList<Person>
Convert to oneMap<String, Integer>
, where name is used as key and age is used as value. usePerson::getName
As a key extraction function,Person::getAge
Extract function as value. Finally, we print out the results.
The above is the detailed content of JavaStream converting List to Map. For more information about converting JavaStream List to Map, please follow my other related articles!