I was trying to filter Entries in HashMap using Streams API, but stuck in last method call Collectors.toMap
. So, I don't have clue to implemement toMap method
public void filterStudents(Map<Integer, Student> studentsMap){
HashMap<Integer, Student> filteredStudentsMap = studentsMap.entrySet().stream().
filter(s -> s.getValue().getAddress().equalsIgnoreCase("delhi")).
collect(Collectors.toMap(k , v));
}
public class Student {
private int id;
private String firstName;
private String lastName;
private String address;
...
}
Any Suggestions?
Since our filter condition requires an int variable we first need to convert Stream of String to Stream of Integer. That's why we called the map() function first. Once we have the Stream of Integer, we can apply maths to find out even numbers. We passed that condition to the filter method.
Once we have the Stream of Integer, we can apply maths to find the even numbers. We passed that condition to filter method. If we needed to filter on String, e.g. select all string which has length > 2, then we would have called filter before map. That's all about how to use map and filter in Java 8.
We can filter a Map in Java 8 by converting the map. entrySet() into Stream and followed by filter() method and then finally collect it using collect() method.
Filter takes a predicate as an argument so basically you are validating your input/collection against a condition, whereas a map allows you to define or use a existing function on the stream eg you can apply String. toUpperCase(...) etc. and transform your inputlist accordingly.
Just generate the output Map
out of the key and value of the entries that pass your filter:
public void filterStudents(Map<Integer, Student> studentsMap){
Map<Integer, Student> filteredStudentsMap =
studentsMap.entrySet()
.stream()
.filter(s -> s.getValue().getAddress().equalsIgnoreCase("delhi"))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With