Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter map and return list of keys

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));
like image 304
IUnknown Avatar asked Dec 12 '19 05:12

IUnknown


People also ask

How do you filter a list of objects using a stream?

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.


2 Answers

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());
like image 142
Andronicus Avatar answered Oct 19 '22 12:10

Andronicus


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());
like image 31
Ravindra Ranwala Avatar answered Oct 19 '22 14:10

Ravindra Ranwala