How to stream and collect instance methods result from an collection of object?

gourab ghosh :

The requirement is to stream a Set of Object, filter on some criteria, and collect only the employeeID in a Set of String

class Employee {
    private String empId;
    private int type;

    public int getType() {
        return type;
    }

    public String getEmpId() {
        return empId;
    }
}

While filtering the following statement

employees.stream().filter(x-> x.getType() == 1).collect(Collectors.toSet());

returns a Set<Employee> instead i want to only collect empId i.e. Set<String>

Note: Cannot make instance variable anything other than private.

Eran :

Use map() to map the Employee instances into the corresponding Employee IDs.

Set<String> empIds =
    employees.stream()
             .filter(x-> x.getType() == 1)
             .map(Employee::getEmpId)
             .collect(Collectors.toSet());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=77346&siteId=1