list嵌套map 使用stream的map方法切割数据
时间: 2023-07-15 12:15:53 浏览: 65
假设你有一个嵌套的List<Map>数据结构,你想使用Stream的map方法来切割数据。下面是一个示例代码:
```java
List<Map<String, Object>> data = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>();
map1.put("name", "Alice");
map1.put("age", 25);
Map<String, Object> map2 = new HashMap<>();
map2.put("name", "Bob");
map2.put("age", 30);
data.add(map1);
data.add(map2);
List<String> names = data.stream()
.map(m -> m.get("name").toString())
.collect(Collectors.toList());
List<Integer> ages = data.stream()
.map(m -> Integer.parseInt(m.get("age").toString()))
.collect(Collectors.toList());
```
在上面的示例中,我们首先创建了一个嵌套的List<Map>数据结构,其中每个Map表示一个人的姓名和年龄。然后,我们使用Stream的map方法来抽取每个Map中的姓名和年龄字段,并分别将它们收集到两个不同的List中。
注意,在使用map方法时,我们需要使用lambda表达式来指定映射函数,以便从每个Map中提取所需的数据。在本例中,我们使用m -> m.get("name").toString()来提取姓名,使用m -> Integer.parseInt(m.get("age").toString())来提取年龄。最后,我们使用Collectors.toList()来将结果收集到List中。
希望这可以帮助你解决问题!
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.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)