stream流把list转为map其中map的值为对象
要使用Stream流将List转换为Map,其中Map的值为对象,可以使用Stream的collect()方法结合Collectors.toMap()方法来实现。
假设有一个包含对象的List,对象具有属性id和name,要将List转换为Map,其中Map的键为id,值为对象本身。
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(1, "Alice"),
new Person(2, "Bob"),
new Person(3, "Charlie")
);
// 使用Stream将List转换为Map,其中Map的值为对象本身
Map<Integer, Person> personMap = personList.stream()
.collect(Collectors.toMap(Person::getId, person -> person));
// 输出Map的内容
personMap.forEach((id, person) -> {
System.out.println("ID: " + id + ", Person: " + person);
});
}
}
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;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
在上面的例子中,我们定义了一个Person类,有id和name两个属性。然后创建一个包含Person对象的List。使用Stream流的collect()方法结合Collectors.toMap()方法将List转换为Map,其中Map的键为id,值为对象本身。
最后,我们使用forEach()方法遍历Map的内容,并输出每个键值对的内容。运行程序,输出结果如下:
ID: 1, Person: Person{id=1, name='Alice'}
ID: 2, Person: Person{id=2, name='Bob'}
ID: 3, Person: Person{id=3, name='Charlie'}
``
原文地址: http://www.cveoy.top/t/topic/iFj2 著作权归作者所有。请勿转载和采集!