# How to filter a Map with Java 8 Stream API

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Dec 17, 2019, updated Oct 8, 2022. Topics: Java.
Canonical URL: https://attacomsian.com/blog/java-filter-map

> This is a short article to learn how to filter map elements using Java 8 Stream API.

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:

```java
// 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:

```java
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:

```bash
Employees with salary > 4000: Alex,Tom,Bena
```

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

```java
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:

```java
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:

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