list转map java8
时间: 2023-06-28 20:04:22 浏览: 98
在Java 8中,可以使用流(Stream)和方法引用(Method Reference)来将List转换为Map。下面是示例代码:
假设有一个Person类,其中包含id和name属性:
```
public 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;
}
}
```
现在有一个Person列表,我们想将其转换为一个Map,其中键是id,值是Person对象。可以使用以下代码:
```
List<Person> personList = Arrays.asList(
new Person(1, "Alice"),
new Person(2, "Bob"),
new Person(3, "Charlie")
);
Map<Integer, Person> personMap = personList.stream()
.collect(Collectors.toMap(Person::getId, person -> person));
// 或者使用方法引用来简化代码
Map<Integer, Person> personMap2 = personList.stream()
.collect(Collectors.toMap(Person::getId, Function.identity()));
```
在上面的代码中,`Collectors.toMap()`方法接受两个参数,第一个参数是Key的生成器,即将Person对象映射到其ID属性。第二个参数是Value的生成器,即直接将Person对象作为值。在第二个参数中,我们还可以使用`Function.identity()`方法来简化代码,因为它返回一个函数,该函数返回其输入参数,即本例中的Person对象。
阅读全文
相关推荐















