java list转map
要将Java中的List转换为Map,可以使用Java 8的Stream API来实现。下面是一个示例代码:
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ListToMapExample {
public static void main(String[] args) {
List<Person> personList = List.of(
new Person("John", 25),
new Person("Jane", 30),
new Person("David", 35)
);
Map<String, Integer> personMap = personList.stream()
.collect(Collectors.toMap(Person::getName, Person::getAge));
System.out.println(personMap);
}
static 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;
}
}
}
在上面的示例中,我们首先创建了一个Person类,它有一个名称和年龄属性。然后,我们创建了一个Person对象的List。接下来,我们使用Stream API的toMap()方法将List转换为Map。在toMap()方法中,我们使用Person::getName作为键的映射函数,使用Person::getAge作为值的映射函数。最后,我们打印输出了转换后的Map。
运行上述代码,输出结果为:
{John=25, Jane=30, David=35}
注意:如果List中存在重复的键,那么在转换为Map时会抛出IllegalStateException异常。可以使用toMap()方法的重载版本,并传递一个合适的合并函数来解决重复键的问题
原文地址: https://www.cveoy.top/t/topic/hNHO 著作权归作者所有。请勿转载和采集!