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

2

5

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.

Nanete answered 27/9, 2021 at 9:34 Comment(2)
What is your java version?Gave
java version 1.8.0Nanete
G
5
users.stream().filter(
    u -> ! departmentIdList.contains(u.getDepartmentId())
).collect(Collectors.toList())
Ger answered 27/9, 2021 at 9:41 Comment(0)
E
8
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

Epiclesis answered 27/9, 2021 at 9:39 Comment(0)
G
5
users.stream().filter(
    u -> ! departmentIdList.contains(u.getDepartmentId())
).collect(Collectors.toList())
Ger answered 27/9, 2021 at 9:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.