In this article, you'll learn how to filter a Map with Java 8 Stream API. Let us say we have the following Map object:

// create a map
Map<String, Integer> employees = new HashMap<>();
employees.put("John", 4000);
employees.put("Alex", 5550);
employees.put("Emma", 3850);
employees.put("Tom", 6000);
employees.put("Bena", 4500);

Filter Map and Return a String

In Java 8 and higher, you can convert Map.entrySet() into a Stream and then use Stream API methods like filter(), map(), and collect(). Here is an example:

String output = employees.entrySet()
        .stream()
        .filter(e -> e.getValue() > 4000)
        .map(e -> e.getKey())
        .collect(Collectors.joining(","));

// print output
System.out.println("Employees with salary > 4000: " +  output);

Here is the output of the above example:

Employees with salary > 4000: Alex,Tom,Bena

Let us have another example to find all those employees whose names match 'Alex' or 'John':

String output = employees.entrySet()
        .stream()
        .filter(e -> e.getKey().equals("Alex") || e.getKey().equals("John"))
        .map(e -> e.getKey())
        .collect(Collectors.joining(","));

Filter Map and Return a Map

Let us have another example to filter a Map by key and return a new Map object:

Map<String, Integer> output = employees.entrySet()
        .stream()
        .filter(e -> e.getValue() > 3000 && e.getValue() < 5000)
        .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));

// print output
System.out.println(output);

The above code will print the following:

{John=4000, Bena=4500, Emma=3850}

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.