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

In this section, 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

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete