为什么 .filter 不从我的 Map<String,Object> 中删除空值

Why is .filter not removing null values from my Map<String,Object>

我正在尝试从我的 LinkedHashMap 中过滤掉不必要的空值。但是它实际上并没有删除这些值。

变量声明

Map<String,Object> dataDictionary = new LinkedHashMap<>();

使用过滤方法后 sysout.print(dataDictionary) 返回的一小部分内容。

[industryCodes=<null>,regionCodes=<null>,andKeywords=false,id= 
<null>,resultsPerPage=20,keywords=<null>,omitKeywords=<null>}

Java代码

dataDictionary= dataDictionary.entrySet()
            .stream()
            .filter(entry -> entry.getValue()!=null)
            .collect(Collectors.toMap(Map.Entry::getKey,
                            Map.Entry::getValue));

希望删除空值及其键,但这似乎没有发生。

你的所作所为完全没有必要。以下足以删除所有 null 值:

dataDictionary.values().removeIf(Objects::isNull);

不需要流等。

编辑:这是我测试过的代码:

Map<String,Object> dataDictionary = new LinkedHashMap<>();
dataDictionary.put("industryCodes", null);
dataDictionary.put("regionCodes", "test");
dataDictionary.put("omitKeywords", null);
dataDictionary.put("resultsPerPage", 21);
dataDictionary.values().removeIf(Objects::isNull);
System.out.println(dataDictionary);

输出:{regionCodes=test, resultsPerPage=21}

注释掉 removeIf 行后,我得到:{industryCodes=null, regionCodes=test, omitKeywords=null, resultsPerPage=21}

似乎对我有用。

也许您的值有问题,它们实际上不为空?

Edit2:根据 Holger 的建议,在 Java 8 之前,您可以使用以下内容:

dataDictionary.values().removeAll(Collections.singleton(null));