我正在尝试从我的LinkedHashMap中过滤出不必要的null值。但是,实际上并没有删除这些值。
变量声明
Map<String,Object> dataDictionary = new LinkedHashMap<>();
使用filter方法后,在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));
期望空值及其键将被删除,但这似乎没有发生。
答案 0 :(得分:5)
您在做什么完全没有必要。以下内容足以删除所有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}
似乎为我工作。
也许您的值有问题,但实际上它们不是null吗?
Edit2:如Holger所建议,在Java 8之前,您可以使用以下代码:
dataDictionary.values().removeAll(Collections.singleton(null));