Learn Java 8 streams with an example - Filter a Map by keys and values

Hello everyone, today we will learn how to filter a Map using the Stream filter() method.

Example 1: Filter Map by Keys

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/*Filter Map by Keys*/
public class DriverClass {
public static void main(String[] args) {
Map<Integer, String> hMap = new HashMap<Integer, String>();
hMap.put(123, "Jessie");
hMap.put(234, "Alpha");
hMap.put(345, "Beta");
hMap.put(456, "Tesla");
hMap.put(111, "Tera");

Map<Integer, String> output = hMap.entrySet()
.stream()
.filter(map -> map.getKey().intValue() <= 254)
.collect(Collectors.toMap(map ->
map.getKey(), map -> map.getValue()));
System.out.println("Output: " + output);
}
}
Output: 



Example 2: Filter Map by Values

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/*Filter Map by Values*/
public class DriverClass {
public static void main(String[] args) {
Map<Integer, String> hMap = new HashMap<Integer, String>();
hMap.put(123, "Tera");
hMap.put(234, "Alpha");
hMap.put(345, "Beta");
hMap.put(456, "Tesla");
hMap.put(111, "Tera");

Map<Integer, String> output = hMap.entrySet()
.stream()
.filter(map -> "Tera".equals(map.getValue()))
.collect(Collectors.toMap(map ->
map.getKey(), map -> map.getValue()));
System.out.println("Output: " + output);
}
}
Output: 



Example 3: Filter Map by both Keys and Values

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/*Filter Map by both Keys and Values*/
public class DriverClass {
public static void main(String[] args) {
Map<Integer, String> hMap = new HashMap<Integer, String>();
hMap.put(193, "Tera");
hMap.put(234, "Alpha");
hMap.put(345, "Beta");
hMap.put(456, "Tesla");
hMap.put(111, "Tera");

Map<Integer, String> output = hMap.entrySet()
.stream()
.filter(map -> "Tera".equals(map.getValue()))
.filter(map ->map.getKey().intValue() <= 150)
.collect(Collectors.toMap(map ->
map.getKey(), map -> map.getValue()));
System.out.println("Output: " + output);
}
}
Output: 



Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring boot video streaming example-HTML5

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Custom Exception Handling in Quarkus REST API

ReactJS, Spring Boot JWT Authentication Example

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring Webflux File Download Example

Node JS mini projects with source code - free download