Java把list实体类转化为map
可以使用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::getId和Person::getName是方法引用,分别表示获取Person对象的id和name属性的方法。
需要注意的是,如果List中存在重复的key,那么在转换为Map时会抛出IllegalStateException异常。如果希望处理重复的key,可以使用Collectors.toMap()方法的第三个参数来指定如何处理重复的key(例如使用第一个value,使用最后一个value,或者自定义逻辑)
原文地址: https://www.cveoy.top/t/topic/iDRV 著作权归作者所有。请勿转载和采集!