Filter nested lists using lambda

I have one List<User> users. I would like to filter the list based on two conditions.

  • UserID Compliance
  • Filter Name Matching

    Public class The user implements Entity {

        public User() {
        }
    
        private String userName;
        private String userId;
        private List<Filter> filters;
    
        public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName;
        }
    
        public String getUserId() {
            return userId;
        }
    
        public void setUserId(String userId) {
            this.userId = userId;
        }
    
        public List<Filter> getFilters() {
            return filters;
        }
    
        public void setFilters(List<Filter> filters) {
            this.filters = filters;
        }
    
    }
    

Here is the method signature

List<User> users = getUsersList();
public List<User> query(String userID,String filterName){
    users.stream().filter(element -> element.getUserID().equals(userID) && element.getFilters().stream().filter(f -> f.getFilterName().equals(filterName))).collect(Collectors.toList());

}

The above method does not work as I am filtering based on element and stream. Can someone help me with the correct way to filter lists and nested lists.

I also tried this way

users.stream().filter(e -> e.getUserId().equals(predicate.getUserID())).collect(Collectors.toList()).stream().filter(f -> f.getFilters().stream().filter(fe -> fe.getName().equals(predicate.getFilterName()))).collect(Collectors.toList());

anyway i get the error below

Type mismatch: cannot convert from Stream to boolean

Tried the offer of Adiel Loingers. He worked

java.util.function.Predicate<Filter> con = e -> e.getName().equals(predicate.getFilterName());
            result = users.stream().filter(p -> p.getUserId().equals(predicate.getUserID()) && p.getFilters().stream().anyMatch(con)).collect(Collectors.toList());
+4
source share
2 answers

You have to change

element.getFilters().stream().filter(f -> f.getFilterName().equals(filterName))

to

element.getFilters().stream().anyMatch(f -> f.getFilterName().equals(filterName))

boolean true , , filter .

+3

, , , , , true, false.

users.stream()
        .filter(element -> element.getUserId().equals(userId)
            && element.getFilters().stream().filter(f -> f.filterName.equals(FilterName)).findAny().isPresent())
        .collect(Collectors.toList());
+1

Source: https://habr.com/ru/post/1688847/


All Articles