4

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.

1
  • 1
    Use map method to convert from Employee to String
    – Jack Flamp
    Apr 4, 2019 at 11:19

3 Answers 3

4

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());
2
employees
   .stream()
   .filter(x-> x.getType() == 1)
   .map(Employee::getEmpId)
   .collect(Collectors.toSet());

will return the Set<String> which contain Employee Ids.

1

If you need the original Employee as well, you can instead use toMap.

Map<String, Employee> employeesById = employees.stream()
        .filter(e-> e.getType() == 1)
        .collect(Collectors.toMap(Employee::getEmpId, Function.identity()));

This is especially useful, if you need to resolve the employees later. If this does not apply, above solutions are to be preferred.

Also, the Set can still be obtained with:

Set<String> employeeIds = employeesById.keySet();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.