可以使用 Java 8 的 Stream API 来将 List 转换为 Map。假设有一个实体类 Person,包含 id 和 name 属性,可以按照以下方式进行转换:

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 = createPersonList();

        // 将List<Person>转换为Map<Integer, String>,其中key为id,value为name
        Map<Integer, String> personMap = personList.stream()
                .collect(Collectors.toMap(Person::getId, Person::getName));

        // 打印Map
        personMap.forEach((id, name) -> System.out.println('id: ' + id + ', name: ' + name));
    }

    private static List<Person> createPersonList() {
        List<Person> personList = List.of(
                new Person(1, 'Alice'),
                new Person(2, 'Bob'),
                new Person(3, 'Charlie')
        );
        return personList;
    }
}

class Person {
    private int id;
    private String name;

    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}

运行上述代码,将输出:

id: 1, name: Alice
id: 2, name: Bob
id: 3, name: Charlie

在上述代码中,使用stream()方法将 List 转换为 Stream,然后使用collect()方法和Collectors.toMap()方法将 Stream 转换为 Map。Person::getIdPerson::getName是方法引用,分别表示获取 Person 对象的 id 和 name 属性的方法。

需要注意的是,如果 List 中存在重复的 key,那么在转换为 Map 时会抛出IllegalStateException异常。如果希望处理重复的 key,可以使用Collectors.toMap()方法的第三个参数来指定如何处理重复的 key(例如使用第一个 value,使用最后一个 value,或者自定义逻辑)。

Java 将 List<实体类> 转换为 Map:高效解决方案

原文地址: https://www.cveoy.top/t/topic/qkub 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录