In this article, we will discuss how to filter a Map by its Key & Value from a Stream using filter() method
1. Filter a Map – Before Java 8 approach :
- A map contains 7 entries with Rank as Key and Value as Cricket Nation
- We are filtering top 3 cricketing nation by its Key using native approach (before Java 8 version)
- Similarly, we are filtering a Map by its value to check whether it contains String called “England“
package net.bench.resources.stream.filter.map;
import java.util.HashMap;
import java.util.Map;
public class FilteringBeforeJava8NativeApproach {
public static void main(String[] args) {
// 1. Map - Rank of top Cricket Nations
Map<Integer, String> rankOfCricketNations = new
HashMap<Integer, String>();
// 1.1 add nations - August-2021 test rankings
rankOfCricketNations.put(1, "New Zealand");
rankOfCricketNations.put(2, "India");
rankOfCricketNations.put(3, "Australia");
rankOfCricketNations.put(4, "England");
rankOfCricketNations.put(5, "Pakistan");
rankOfCricketNations.put(6, "South Africa");
rankOfCricketNations.put(7, "West Indies");
// 1.2 iterate and print original Map
System.out.println("All Cricket nations are :-\n");
for(Map.Entry<Integer, String> entry : rankOfCricketNations.entrySet()) {
System.out.println("Rank: " + entry.getKey()
+ "\tCountry: " + entry.getValue());
}
// store result in filtered Map
Map<Integer, String> filteredMap = new HashMap<>();
// 2. Key - get top 3 nations
for(Map.Entry<Integer, String> entry : rankOfCricketNations.entrySet()) {
// filter to get top 3 nations
if(entry.getKey() <= 3) {
filteredMap.put(entry.getKey(), entry.getValue());
}
}
// 2.1 Iterate and print to console after filtering
System.out.println("\n\nKey filtering - Top 3 Cricket nation are :-\n");
for(Map.Entry<Integer, String> entry : filteredMap.entrySet()) {
System.out.println("Rank: " + entry.getKey()
+ "\tCountry: " + entry.getValue());
}
// 2.2 clear filteredMap
filteredMap.clear();
// 3. Value - get nations on comparison
for(Map.Entry<Integer, String> entry : rankOfCricketNations.entrySet()) {
// filter by value
if(entry.getValue().contains("England")) {
filteredMap.put(entry.getKey(), entry.getValue());
}
}
// 3.1 Iterate and print to console after filtering
System.out.println("\n\nValue - Filter by country :-\n");
for(Map.Entry<Integer, String> entry : filteredMap.entrySet()) {
System.out.println("Rank: " + entry.getKey()
+ "\tCountry: " + entry.getValue());
}
}
}
Output:
All Cricket nations are :-
Rank: 1 Country: New Zealand
Rank: 2 Country: India
Rank: 3 Country: Australia
Rank: 4 Country: England
Rank: 5 Country: Pakistan
Rank: 6 Country: South Africa
Rank: 7 Country: West Indies
Key filtering - Top 3 Cricket nation are :-
Rank: 1 Country: New Zealand
Rank: 2 Country: India
Rank: 3 Country: Australia
Value - Filter by country :-
Rank: 4 Country: England
2. Java 8 – Filter a Map by its Key :
- A map contains 7 entries with Rank as Key and Value as Cricket Nation
- We are filtering top 3 cricketing nation by its Key using Java 8 Stream filter() by passing Predicate
- Storing the result after filtering into a new Map
- Finally, printing to console using Stream’s forEach() method
package net.bench.resources.stream.filter.map;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class StreamFilterMapByKeys {
public static void main(String[] args) {
// Map - Rank of top Cricket Nations
Map<Integer, String> rankOfCricketNations = new
HashMap<Integer, String>();
// add nations - August-2021 test rankings
rankOfCricketNations.put(1, "New Zealand");
rankOfCricketNations.put(2, "India");
rankOfCricketNations.put(3, "Australia");
rankOfCricketNations.put(4, "England");
rankOfCricketNations.put(5, "Pakistan");
rankOfCricketNations.put(6, "South Africa");
rankOfCricketNations.put(7, "West Indies");
// iterate and print original Map
System.out.println("All Cricket nations are :-\n");
for(Map.Entry<Integer, String> entry : rankOfCricketNations.entrySet()) {
System.out.println("Rank: " + entry.getKey()
+ "\tCountry: " + entry.getValue());
}
// filter top 3 nation by its Rank(key)
Map<Integer, String> filteredMap = rankOfCricketNations
.entrySet()
.stream()
.filter(entry -> entry.getKey() <= 3)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
// Iterate and print to console after filtering
System.out.println("\n\nKey filtering - Top 3 Cricket nation are :-\n");
filteredMap
.entrySet()
.stream()
.forEach(entry -> System.out.println("Rank: " + entry.getKey()
+ "\tCountry: " + entry.getValue()));
}
}
Output:
All Cricket nations are :-
Rank: 1 Country: New Zealand
Rank: 2 Country: India
Rank: 3 Country: Australia
Rank: 4 Country: England
Rank: 5 Country: Pakistan
Rank: 6 Country: South Africa
Rank: 7 Country: West Indies
Key filtering - Top 3 Cricket nation are :-
Rank: 1 Country: New Zealand
Rank: 2 Country: India
Rank: 3 Country: Australia
3. Java 8 – Filter a Map by its Value :
- A map contains 7 entries with Rank as Key and Value as Cricket Nation
- We are filtering a Map by its Value using Java 8 Stream filter() by passing Predicate for value comparison
- Here, we are checking whether value contains is “England”
- Storing the result after filtering into a new Map
- Finally, printing to console using Stream’s forEach() method
package net.bench.resources.stream.filter.map;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class StreamFilterMapByValues {
public static void main(String[] args) {
// Map - Rank of top Cricket Nations
Map<Integer, String> rankOfCricketNations = new
HashMap<Integer, String>();
// add nations - August-2021 test rankings
rankOfCricketNations.put(1, "New Zealand");
rankOfCricketNations.put(2, "India");
rankOfCricketNations.put(3, "Australia");
rankOfCricketNations.put(4, "England");
rankOfCricketNations.put(5, "Pakistan");
rankOfCricketNations.put(6, "South Africa");
rankOfCricketNations.put(7, "West Indies");
// iterate and print original Map
System.out.println("All Cricket nations are :-\n");
for(Map.Entry<Integer, String> entry : rankOfCricketNations.entrySet()) {
System.out.println("Rank: " + entry.getKey()
+ "\tCountry: " + entry.getValue());
}
// filter by Value - counties which has 2 words
Map<Integer, String> filteredMap = rankOfCricketNations
.entrySet()
.stream()
.filter(entry -> entry.getValue().contains("England"))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
// Iterate and print to console after filtering
System.out.println("\n\nValue - Filter by country :-\n");
filteredMap
.entrySet()
.stream()
.forEach(entry -> System.out.println("Rank: " + entry.getKey()
+ "\tCountry: " + entry.getValue()));
}
}
Output:
All Cricket nations are :-
Rank: 1 Country: New Zealand
Rank: 2 Country: India
Rank: 3 Country: Australia
Rank: 4 Country: England
Rank: 5 Country: Pakistan
Rank: 6 Country: South Africa
Rank: 7 Country: West Indies
Value - Filter by country :-
Rank: 4 Country: England
4. Java 8 – Filter a Map by both Key & Value :
- A map contains 7 entries with Rank as Key and Value as Cricket Nation
- In this example, we are filtering a Map by both its Key and Value by passing 2 Predicate conditions with logical AND (&&)
- First, it will evaluate on the basis of Key that whether rank is under 3 and then second condition is evaluated to check whether Nation name starts with “I” for Value comparison
- For above Predicate conditions, we got 1 result which is India and its Rank is 2
- Note: Likewise we can combine one or more Predicate condition based on our requirement with logical AND, OR, etc.
package net.bench.resources.stream.filter.map;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class StreamFilterMapByKeysAndValues {
public static void main(String[] args) {
// Map - Rank of top Cricket Nations
Map<Integer, String> rankOfCricketNations = new
HashMap<Integer, String>();
// add nations - August-2021 test rankings
rankOfCricketNations.put(1, "New Zealand");
rankOfCricketNations.put(2, "India");
rankOfCricketNations.put(3, "Australia");
rankOfCricketNations.put(4, "England");
rankOfCricketNations.put(5, "Pakistan");
rankOfCricketNations.put(6, "South Africa");
rankOfCricketNations.put(7, "West Indies");
// iterate and print original Map
System.out.println("All Cricket nations are :-\n");
for(Map.Entry<Integer, String> entry : rankOfCricketNations.entrySet()) {
System.out.println("Rank: " + entry.getKey()
+ "\tCountry: " + entry.getValue());
}
// filter top 3 nation by its Rank(key)
Map<Integer, String> filteredMap = rankOfCricketNations
.entrySet()
.stream()
.filter(entry -> entry.getKey() <= 3 && entry.getValue().startsWith("I"))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
// Iterate and print to console after filtering
System.out.println("\n\nCountry starts with 'I' and Rank under 3 :-\n");
filteredMap
.entrySet()
.stream()
.forEach(entry -> System.out.println("Rank: " + entry.getKey()
+ "\tCountry: " + entry.getValue()));
}
}
Output:
All Cricket nations are :-
Rank: 1 Country: New Zealand
Rank: 2 Country: India
Rank: 3 Country: Australia
Rank: 4 Country: England
Rank: 5 Country: Pakistan
Rank: 6 Country: South Africa
Rank: 7 Country: West Indies
Country starts with 'I' and Rank under 3 :-
Rank: 2 Country: India
5. Java 8 – Filtering a Map & Joining :
- A map contains 7 entries with Rank as Key and Value as Cricket Nation
- In this example, we are filtering a Map by both its Key for all Nation whose rank is under 3
- Mapping the resulting Values (Nation name) into a String by Collectors.joining() with comma(,) as separation between 2 values and prefix as opening curly-braces ‘{‘ and postfix as closing curly-braces ‘}‘
package net.bench.resources.stream.filter.map;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class MapFiltertingAndJoining {
public static void main(String[] args) {
// 1. Map - Rank of top Cricket Nations
Map<Integer, String> rankOfCricketNations = new
HashMap<Integer, String>();
// 1.1 add nations - August-2021 test rankings
rankOfCricketNations.put(1, "New Zealand");
rankOfCricketNations.put(2, "India");
rankOfCricketNations.put(3, "Australia");
rankOfCricketNations.put(4, "England");
rankOfCricketNations.put(5, "Pakistan");
rankOfCricketNations.put(6, "South Africa");
rankOfCricketNations.put(7, "West Indies");
// 1.2 iterate and print original Map
System.out.println("All Cricket nations are :-\n");
for(Map.Entry<Integer, String> entry : rankOfCricketNations.entrySet()) {
System.out.println("Rank: " + entry.getKey()
+ "\tCountry: " + entry.getValue());
}
// 2. Map filtering by values and joining
String result = rankOfCricketNations
.entrySet()
.stream()
.filter(entry -> entry.getKey() > 3)
.map(map -> map.getValue())
.collect(Collectors.joining(", ", "{", "}"));
// 2.1 print to console
System.out.println("\n\nFiltering & Joining - Countries with Rank above 3: \n"
+ result);
}
}
Output:
All Cricket nations are :-
Rank: 1 Country: New Zealand
Rank: 2 Country: India
Rank: 3 Country: Australia
Rank: 4 Country: England
Rank: 5 Country: Pakistan
Rank: 6 Country: South Africa
Rank: 7 Country: West Indies
Filtering & Joining - Countries with Rank above 3:
{England, Pakistan, South Africa, West Indies}
References:
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
- https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html
Happy Coding !!
Happy Learning !!