Following map, having both key-value pair as String, Write a logic to filter all the null values from Map without using any external API's ?
Is there any other approach than traversing through whole map and filtering out the values (Traversing whole map and getting Entry Object and discarding those pair) ?
Map<String,String> map = new HashMap<String,String>(); map.put("1", "One"); map.put("2", "Two"); map.put("3", null); map.put("4", "Four"); map.put("5", null); //Logic to filer values //Post filtering It should print only ( 1,2 & 4 pair )
How do you pass in null values into a HashMap? The following code snippet works with options filled in: HashMap<String, String> options = new HashMap<String, String>(); options. put("name", "value"); Person person = sample.
HashMap allows one null key and multiple null values whereas Hashtable doesn't allow any null key or value.
You can use the Java 8 method Collection.removeIf
for this purpose:
map.values().removeIf(Objects::isNull);
This removed all values that are null.
Online demo
This works by the fact that calling .values()
for a HashMap returns a collection that delegated modifications back to the HashMap itself, meaning that our call for removeIf()
actually changes the HashMap (this doesn't work on all java Map's)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With