MA-Dev
MA-Dev

Reputation: 171

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.

Upvotes: 7

Views: 14694

Answers (2)

30thh
30thh

Reputation: 11376

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

Upvotes: 5

Noixes
Noixes

Reputation: 1178

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

Upvotes: 9

Related Questions