List<Map<String, String>>只保留map中某些字段,其他字段删除
时间: 2023-11-11 11:09:00 浏览: 172
可以使用Stream API来实现这个功能,示例代码如下:
```java
List<Map<String, String>> list = new ArrayList<>();
Map<String, String> map1 = new HashMap<>();
map1.put("name", "Alice");
map1.put("age", "20");
map1.put("gender", "female");
list.add(map1);
Map<String, String> map2 = new HashMap<>();
map2.put("name", "Bob");
map2.put("age", "30");
map2.put("gender", "male");
list.add(map2);
// 只保留 name 和 gender 字段
List<Map<String, String>> resultList =
list.stream()
.map(map -> {
Map<String, String> resultMap = new HashMap<>();
resultMap.put("name", map.get("name"));
resultMap.put("gender", map.get("gender"));
return resultMap;
})
.collect(Collectors.toList());
System.out.println(resultList);
```
输出结果为:
```
[{name=Alice, gender=female}, {name=Bob, gender=male}]
```
阅读全文