We have a Map<String, Student> studentMap
, where Student
is a class as follows:
class Student{
String name;
int age;
}
We need to return a list of all Ids eligibleStudents
, where the age > 20.
Why does the following give a compilation error at the Collectors.toList
:
HashMap<String, Student> studentMap = getStudentMap();
eligibleStudents = studentMap .entrySet().stream()
.filter(a -> a.getValue().getAge() > 20)
.collect(Collectors.toList(Entry::getKey));
Java stream provides a method filter() to filter stream elements on the basis of given predicate. Suppose you want to get only even elements of your list then you can do this easily with the help of filter method. This method takes predicate as an argument and returns a stream of consisting of resulted elements.
Collectors.toList()
does not take any argument, you need to map
it first:
eligibleStudents = studentMap.entrySet().stream()
.filter(a -> a.getValue().getAge() > 20)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
toList()
collector just creates a container to accumulate elements and takes no arguments. You need to do a mapping before it is collected. Here's how it looks.
List<String> eligibleStudents = studentMap.entrySet().stream()
.filter(a -> a.getValue().getAge() > 20)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
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