Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter "Null" values from HashMap<String, String>? [duplicate]

Tags:

java

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 )   
like image 742
RaBa Avatar asked Mar 08 '16 09:03

RaBa


People also ask

How HashMap handle null values?

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.

Can HashMap take null values?

HashMap allows one null key and multiple null values whereas Hashtable doesn't allow any null key or value.


1 Answers

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)

like image 78
Ferrybig Avatar answered Oct 05 '22 07:10

Ferrybig