In this tutorial, we will see “How to Filter a Map by Key & Value using Java 8 Stream API?”

Filter a Map in Java 8 with examples...!!! Share on X

Example 1. Filter a Map by Key

/**
 * Filter Map by Key 
 * @author Deepak Verma
 *
 */
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;

public class Filter_Map_By_Key_Java8 {

	public static void main(String[] args) {

		Map<Integer, String> studentsMap = new HashMap<Integer, String>(); 
		
		studentsMap.put(43, "Yash"); 
		studentsMap.put(98, "Sam"); 
		studentsMap.put(61, "Gaurangee");  
		studentsMap.put(15, "Danny");
		studentsMap.put(87, "Chris"); 
		studentsMap.put(22, "Perry"); 
		studentsMap.put(35, "Yashika");  
		studentsMap.put(58, "Lizzie");

		Map<Integer, String> result = studentsMap.entrySet() 
				                                 .stream() 
				                                 .filter(x -> x.getKey().intValue() >= 40) 
				                                 .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));  

		System.out.println("Students who scored more than the passing threshold of 40: \n\n" + result);
	}
}

Output:

Students who scored more than the passing threshold of 40: 

{98=Sam, 87=Chris, 58=Lizzie, 43=Yash, 61=Gaurangee}

 

Example 2. Filter a Map by Value

/**
 * Filter Map by Value 
 * @author Deepak Verma
 *
 */
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;

public class Filter_Map_By_Value_Java8 {

	public static void main(String[] args) {

		Map<Integer, String> studentsMap = new HashMap<Integer, String>(); 

		studentsMap.put(43, "Yash"); 
		studentsMap.put(98, "Sam"); 
		studentsMap.put(61, "Gaurangee");  
		studentsMap.put(15, "Danny");
		studentsMap.put(87, "Chris"); 
		studentsMap.put(22, "Perry"); 
		studentsMap.put(35, "Yashika");  
		studentsMap.put(58, "Lizzie");

		Map<Integer, String> result = studentsMap.entrySet()
				                                 .stream()
				                                 .filter(x -> (x.getValue().equals("Danny")))
				                                 .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));

		System.out.println("Danny scored : " + result.keySet());
	}
}

Output:

Danny scored : [15]

Filter a Map in Java 8 with examples...!!! Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

java 8 filter map by key

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts