javajava-stream

Java Stream filter a object list which does not contains a particular List of items as property


I have a List of users.

public class User {
private String UserID;
private String departmentId;
private String email;
}

And I have a list of departmentIds

List<String> departmentIdList = Arrays.asList("111", "2222");

I need to filter the users with department Id not in the departmentIdList. As per above example I need users whose department ID not equal to 111 or 2222.


Solution

  • users.stream().filter(
        u -> ! departmentIdList.contains(u.getDepartmentId())
    ).collect(Collectors.toList())