import java.util.*;
import java.util.stream.Collectors;
public class ListToMapExample {
public static void main(String[] args) {
// 创建一个包含多个对象的列表
List<Person> personList = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
);
// 将列表转换为Map,使用姓名作为键,Person对象作为值
Map<String, Person> personMap = personList.stream()
.collect(Collectors.toMap(Person::getName, person -> person));
// 打印结果
personMap.forEach((key, value) -> System.out.println(key + " : " + value));
}
}
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;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + '}';
}
}
Person 对象的列表 personList。Collectors.toMap 方法将列表转换为 Map。这里我们将 Person 对象的 name 属性作为键,Person 对象本身作为值。personMap 并打印每个键值对来验证转换结果。如果你有更多问题或需要进一步的帮助,请告诉我!
上一篇:java http请求工具类
下一篇:java set 转 list
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站