I'm trying to filter out unnecessary null values from my LinkedHashMap. However it isn't actually removing these values.
Variable declaration
Map<String,Object> dataDictionary = new LinkedHashMap<>();
Small section of what is being returned when i sysout.print(dataDictionary) after using the filter method.
[industryCodes=<null>,regionCodes=<null>,andKeywords=false,id=
<null>,resultsPerPage=20,keywords=<null>,omitKeywords=<null>}
Java code
dataDictionary= dataDictionary.entrySet()
.stream()
.filter(entry -> entry.getValue()!=null)
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue));
Expecting the null values and their keys to be removed but this doesn't seem to be happening.
What you're doing is totally unnecessary. The following is enough to remove all null
values:
dataDictionary.values().removeIf(Objects::isNull);
No need for streams and such.
Edit: Here is the code I've tested it with:
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);
Output: {regionCodes=test, resultsPerPage=21}
With the removeIf
line commented out I get: {industryCodes=null, regionCodes=test, omitKeywords=null, resultsPerPage=21}
Seems to be working for me.
Maybe there is something wrong with your values and they actually aren't null?
Edit2: As suggested by Holger, before Java 8 you can use the following:
dataDictionary.values().removeAll(Collections.singleton(null));