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

Time:09-27

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.

CodePudding user response:

List<User> users = new ArrayList<>();

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

List<User> usersNotInDepartments = users.stream()
        .filter(u -> !departmentIdList.contains(u.departmentId))
        .collect(Collectors.toList());

I would suggest that you make the departmentIdList to a Set data structure since it is more performant than Lists on lookup

CodePudding user response:

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