java list转map stream
时间: 2024-04-27 16:17:22 浏览: 10
在Java中,可以使用Stream API将List转换为Map。下面是一个示例代码:
```java
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ListToMapExample {
public static void main(String[] args) {
List<Person> personList = List.of(
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 35)
);
// 使用Stream的collect方法将List转换为Map
Map<String, Integer> personMap = personList.stream()
.collect(Collectors.toMap(Person::getName, Person::getAge));
// 打印转换后的Map
System.out.println(personMap);
}
static 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;
}
}
}
```
上述代码中,我们定义了一个Person类,包含姓名和年龄两个属性。然后创建了一个Person对象的List。通过使用Stream的`collect`方法,结合`Collectors.toMap`方法,可以将List转换为Map。在`toMap`方法中,我们指定了键和值的提取方式,这里使用了`Person::getName`和`Person::getAge`方法引用。
运行上述代码,输出结果为:
```
{Alice=25, Bob=30, Charlie=35}
```