java8中list转map怎么实现

   2024-10-29 5210
核心提示:在Java 8中,可以使用Collectors.toMap()方法将List转换为Map。以下是一个简单的示例代码:假设有一个类Person:public class Pe

在Java 8中,可以使用Collectors.toMap()方法将List转换为Map。以下是一个简单的示例代码:

假设有一个类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}

现在有一个List,我们想将其转换为Map,其中key为name,value为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);    }}

上面的代码中,我们使用personList.stream().collect(Collectors.toMap(Person::getName, Person::getAge))将List转换为Map<String, Integer>,其中key为name,value为age。

请注意,如果List中存在重复的key,则会抛出IllegalStateException异常。您可以使用另一个Collectors.toMap()方法重载,指定一个合并函数来处理重复key的情况。

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号