java - 列表映射的过滤器映射
问题描述
我有一个 HashMap 类型:
Map<String, Map<String, List<MyPojo>>> myMap;
MyPojo
有一个元素String domain
。
在某些情况下,此域可以为空。
我想过滤我的地图,以便所有子地图Map<String, List<MyPojo>>
都不应该有空域。
解决方案
开场白:你可能不应该有一个Map<String, Map<String, List<MyPojo>>>
- 这太令人费解了。这里应该有更多的写出类型。也许一个Map<String, Students>
或一些这样的。您的问题并不清楚您的问题域是什么,所以我只能说您的起始类型可能不是好的代码风格。
让我们来回答你的问题:
如果你的意思filter
是在 juStream 的过滤器中,那么你不能。该Map
接口没有removeIf
,并且流/过滤器的东西不是要更改现有类型,而只是要制作新的东西。任何修改底层映射的尝试都会得到 ConcurrentModificationExceptions。
这是“就地”更改地图的方法
var it = myMap.entrySet().iterator();
while (it.hasNext()) {
if (it.next().getValue().values().stream()
// we now have a stream of lists.
.anyMatch(
list -> list.stream().anyMatch(mp -> mp.getDomain() == null))) {
it.remove();
}
}
您在这里有一个嵌套的 anyMatch 操作:如果子图中的任何条目包含一个列表,而该列表的任何条目都具有空域,则您希望删除 ak/v 对。
让我们看看它的实际效果:
import java.util.*;
import java.util.stream.*;
@lombok.Value class MyPojo {
String domain;
}
class Test { public static void main(String[] args) {
Map<String, Map<String, List<MyPojo>>> myMap = new HashMap<>();
myMap.put("A", Map.of("X", List.of(), "Y", List.of(new MyPojo(null))));
myMap.put("B", Map.of("V", List.of(), "W", List.of(new MyPojo("domain"))));
System.out.println(myMap);
var it = myMap.entrySet().iterator();
while (it.hasNext()) {
if (it.next().getValue().values().stream()
// we now have a stream of lists.
.anyMatch(
list -> list.stream().anyMatch(mp -> mp.getDomain() == null))) {
it.remove();
}
}
System.out.println(myMap);
}}
鉴于上述情况,生成新地图的代码并不难理解。
推荐阅读
- reactjs - 如何使用一个 div 在 ReactJS 选项卡中输出动态内容?
- mysql - 如何获得多层次营销(树)子数量
- c# - 如何修复“需要一个值但请求中不存在值”异常?
- javascript - 当点击事件发生类更改时,如何使用 document.getElementsByClassName 获取元素?
- mysql - MySQL返回我只想设置值的数据
- django - 登录后 Django 2.1 测试用例客户端未经授权
- java - JSON 注入将未经验证的输入写入 JSON
- php - 当通过 Ajax 进行 POST 时,Laravel 5.6 CSRF 令牌失败
- algorithm - 烛台价格图表中的高/低检测
- python - 带有 eps 的 Matplotlib savefig 不会在 3d 图上的投影平面中绘制网格线