Java 8 – Filter a Map examples

Category : Java | Sub Category : Java 8 Features | By Runner Dev Last updated: 2020-09-30 15:36:13 Viewed : 285


Java 8 – Filter a Map examples

 How to filter a Map with Java 8 stream API:

public class HashMap<K,V> extends AbstractMap<K,V>

    implements Map<K,V>, Cloneable, Serializable {}


1. Before Java 8 :

FilterMapExample .java

 

 import java.util.HashMap;

import java.util.Map;

 

public class FilterMapExample {

     public static void main(String[] args) {

           Map<Integer, String> animalMap = new HashMap<>();

           animalMap.put(1, "Ant");

           animalMap.put(2, "Bat");

           animalMap.put(2, "Cat");

 

           String animalName = "";

      for (Map.Entry<Integer, String> entry : animalMap.entrySet()) {

                if ("Cat".equals(entry.getValue())) {

                      animalName = entry.getValue();

                }

           }

           System.out.println("animalName=> " + animalName);

     }

 

}

 


Output:

  animalName=> Cat

 

2. Java 8 – Filter a Map

With Java 8, convert a Map.entrySet() into a stream, follow by a filter() and collect() 

FilterMapExample .java 

 import java.util.HashMap;

import java.util.Map;

import java.util.stream.Collectors;

 

public class FilterMapExample {

     public static void main(String[] args) {

   Map<Integer, String> animalMap = new HashMap<>();

      animalMap.put(1, "Ant");

      animalMap.put(2, "Bat");

      animalMap.put(3, "Cat");

          

// Map -> Stream -> Filter -> String

String resultStr = animalMap.entrySet().stream()

             .filter(x ->    "Ant".equals(x.getValue()))

              .map(x -> x.getValue()).collect(Collectors.joining());

System.out.println("resultStr " + resultStr);

 

// Map -> Stream -> Filter -> MAP

Map<Integer, String> collectMap = animalMap.entrySet().stream()

        .filter(x -> x.getKey() == 2)

       .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));

System.out.println("collectMap " + collectMap);

 

// or alternate way like this

Map<Integer, String> collectMap1 = animalMap.entrySet().stream()

   .filter(x -> x.getKey() == 3)

   .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

 System.out.println("collectMap1 " + collectMap1);

     }

}

 


OutPut:

    resultStr Ant

    collectMap {2=Bat}

    collectMap1 {3=Cat}

 

3 . Java 8 – Filter a Map  and Predicate example

FilterMapExample1 .java

 

 import java.util.HashMap;

import java.util.Map;

import java.util.function.Predicate;

import java.util.stream.Collectors;

 

public class FilterMapExample1 {

   public static void main(String[] args) {

   Map<Integer, String> animalMap = new HashMap<>();

        animalMap.put(1, "Ant");

        animalMap.put(2, "Bat");

        animalMap.put(3, "Cat");

 

     // Map -> Stream -> String //Join with comma

 String resultStr = animalMap.entrySet().stream().map(x ->  x.getValue()).collect(Collectors.joining(","));

           System.out.println("resultStr " + resultStr);

 

     // Map -> Stream -> Filter -> MAP

Map<Integer, String> collectMap = animalMap.entrySet().stream()

 .filter(map -> map.getKey() <= 3)

 .collect(Collectors.toMap(Map.Entry::getKey,  Map.Entry::getValue));

           System.out.println("collectMap " + collectMap);

 

    // Java 8 Predicate example

Map<Integer, String> predicateMap = filterByValue(animalMapx -> (x.contains("Cat") && !x.contains("Bat")));

           System.out.println(predicateMap);

     }

 

     // Generic Map filterbyvalue, with predicate

public static <K, V> Map<K, V> filterByValue(Map<K, V> map, Predicate<V> predicate) {

return map.entrySet().stream().filter(x -> predicate.test(x.getValue()))

.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

     }

}

 


OutPut:

  resultStr Ant,Bat,Cat

  collectMap {1=Ant, 2=Bat, 3=Cat}

  {3=Cat}

Search
Related Articles

Leave a Comment: