首页 > 解决方案 > 列表映射的过滤器映射

问题描述

我有一个 HashMap 类型:

Map<String, Map<String, List<MyPojo>>> myMap;

MyPojo有一个元素String domain

在某些情况下,此域可以为空。

我想过滤我的地图,以便所有子地图Map<String, List<MyPojo>>都不应该有空域。

标签: javajava-stream

解决方案


开场白:你可能不应该有一个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);

}}

鉴于上述情况,生成新地图的代码并不难理解。


推荐阅读