How to filter a map with Java Stream?


class Person {
	private Integer age;
	private String name;
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Person(Integer age, String name) {
		super();
		this.age = age;
		this.name = name;
	}
	@Override
	public String toString() {
		return "Person [age=" + age + ", name=" + name + "]";
	}

}


import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class JavaStreamMapFilter {

	public static void main(String[] args) {

		
		//Example of stream filter return  String
		Map<String, String> nameMap  = new HashMap<>();
		nameMap.put("JL", "Jack Lee");
		nameMap.put("JM", "Jack Ma");
		nameMap.put("SL", "Steve Liu");
		nameMap.put("AX", "Alice Xu");
 
        String result = nameMap.entrySet().stream()
                .filter(map -> "Jack Ma".equals(map.getValue()))
                .map(map -> map.getValue())
                .collect(Collectors.joining());

        System.out.println("\n\nResult : " + result);
		
		//Example of stream filter return  a Map
        Map<String, Person>   peopleMap = getMap();
		System.out.println("Initial  map :  ");
		peopleMap.forEach((k, v) -> System.out.println(k + ":" + v));
		Map<String, Person> oldPeopleMap = peopleMap.entrySet().stream().filter(p -> p.getValue().getAge() > 30)
				.collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));

		System.out.println("\n\nAfter filtering, here is the map :  ");
		oldPeopleMap.forEach((k, v) -> System.out.println(k + ":" + v));
	}

	private static Map<String, Person> getMap() {
		Map<String, Person> peopleMap = new HashMap<>();
		Person person1 = new Person(21, "Jack Lee");
		peopleMap.put("JL", person1);
		Person person2 = new Person(31, "Jack Ma");
		peopleMap.put("JM", person2);
		Person person3 = new Person(12, "Steve Liu");
		peopleMap.put("SL", person3);
		Person person4 = new Person(42, "Alice XU");
		peopleMap.put("AX", person4);

		return peopleMap;
	}

}



Here the output:

Result : Jack Ma
Initial  map :  
JL:Person [age=21, name=Jack Lee]
JM:Person [age=31, name=Jack Ma]
AX:Person [age=42, name=Alice XU]
SL:Person [age=12, name=Steve Liu]


After filtering, here is the map :  
JM:Person [age=31, name=Jack Ma]
AX:Person [age=42, name=Alice XU]