gpt4 book ai didi

java - 为什么 .filter 不从我的 Map 中删除空值

转载 作者:行者123 更新时间:2023-12-03 19:10:21 25 4
gpt4 key购买 nike

我正在尝试从我的 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));

关于java - 为什么 .filter 不从我的 Map<String,Object> 中删除空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55847859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com