In this tutorial, we will see “How to filter null values from Map in Java 8?”. In order to remove null from the hashmap, we are going to use Stream API introduced in Java 8.
In the below specified example, I’ve explained 2 different code approaches to achieve the same output:
- Anonymous Implementation
- Lambda Implementation
Filter/Remove null values from a Map using Stream in Java 8...!!! Click To Tweet
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.function.Consumer; import java.util.function.Predicate; public class Filter_Null_Map_Java8_Stream_Example { public static void main(String[] args) { Map <Integer, String> map = new HashMap <Integer, String> (); map.put(65, "noni"); map.put(33, "yogi"); map.put(73, "dv"); map.put(46, "null"); map.put(37, "isha"); map.put(98, "null"); map.put(54, "yashu"); //Original Map System.out.println("Original Map:\n"); map.entrySet().stream().forEach(System.out::println); //Map after removing 'Null' //Anonymous Implementation System.out.println("\nNew Map after removing 'null' (Anonymous Impl):\n"); map.entrySet().stream().filter(new Predicate < Map.Entry < Integer, String >> () { @Override public boolean test(Entry <Integer, String> t) { return !t.getValue().contains("null"); } }).forEach(new Consumer <Map.Entry <Integer, String>> () { @Override public void accept(Entry <Integer, String> t) { System.out.println(t); } }); System.out.println("\n"); //Map after removing 'Null' //Lambda Implementation System.out.println("New Map after removing 'null' (Lambda Impl):\n"); map.entrySet().stream().filter(t -> !t.getValue().contains("null")).forEach(t -> System.out.println(t)); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | Original Map: 65=noni 33=yogi 98=null 37=isha 54=yashu 73=dv 46=null New Map after removing 'null' (Anonymous Impl): 65=noni 33=yogi 37=isha 54=yashu 73=dv New Map after removing 'null' (Lambda Impl): 65=noni 33=yogi 37=isha 54=yashu 73=dv |
Filter/Remove null values from a Map using Stream in Java 8...!!! Click To Tweet
Do you like this Post? – then check my other helpful posts:
- Double the even / odd numbers of a specified ArrayList using Streams
- Double the numbers of specified ArrayList using Streams