stream list 转 map对象
时间: 2024-01-31 14:04:32 浏览: 88
可以使用Java 8的Stream API将List转换为Map对象。下面是一个示例代码:
```java
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
// 假设有一个User类,包含id、name和age属性
List<User> userList = getUserList();
// 将List转换为Map,以id作为key,name作为value
Map<Integer, String> userMap = userList.stream()
.collect(Collectors.toMap(User::getId, User::getName));
// 输出转换后的Map对象
System.out.println(userMap);
}
private static List<User> getUserList() {
// 创建一个包含User对象的List
List<User> userList = List.of(
new User(1, "Alice", 25),
new User(2, "Bob", 30),
new User(3, "Charlie", 35)
);
return userList;
}
static class User {
private int id;
private String name;
private int age;
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
}
```
这段代码将List<User>转换为Map<Integer, String>,其中id作为key,name作为value。你可以根据自己的需求修改代码中的User类和转换逻辑。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)