Java Spring 中,可以使用 Collectors.toMap()
方法将一个列表转换为 Map。假设我们有一个 Person 类型的对象列表,其中每个 Person 对象都有一个唯一的 ID 和一个姓名属性 name,我们可以使用以下代码将它们转换为 ID-Name 的键值对:
List<Person> personList = new ArrayList<>();
// TODO: add person objects to the list
Map<Integer, String> idNameMap = personList.stream()
.collect(Collectors.toMap(Person::getId, Person::getName));
System.out.println(idNameMap);
这里使用 stream()
方法将列表转换为流,然后使用 Collectors.toMap()
将每个 Person 对象的 ID 和名称转换为一个键值对,并将这些键值对收集到一个 Map 中。其中 Person::getId
和 Person::getName
是方法引用,分别代表获取 Person 对象中的 ID 和 name 属性。