How do I filter the collection correctly in stream?

Viewed 66

The method comes with a map with the user name key and a Boolean value. The user names are the same as in the database.From the database comes a list of entities in which the user name and password. I need to compare the user names from the list of entities and the user names from the map in the flow and leave only those entities that have the same user name and the value " true"

public class BasicAuthUser {   
    private String username;
    private String password;
}


private void create(Map<String, Boolean> users) {
    var allUsersFromDB = basicAuthUserService.getAllUsers(); //List<BasicAuthUsers>
    var credentials = allUsersFromDB.stream()
        .filter ( ? )//basicAuthUser.getUsername().equals(users.getKey)&&users.getValue.equals(Boolean.TRUE)
        .map(user -> user.getUsername(),user.getPassword())
        .collect(Collectors.joining());
}
2 Answers
.filter(user -> {
    Boolean inMap = users.getOrDefault(user.getUsername(), false);
    return Boolean.TRUE.equals(inMap);
})  

If the List is modifiable, you can use

allUsersFromDb.removeIf(u -> !users.getOrDefault(u.getUserName(), false));

Else, you can go ahead with filter and collect as suggested in other answers.

PS: Better sensible alternate would be to push this work to DB itself and retrieve only those users which are present in Map with value true.

Before constructing the query, you can filter the input map to remove all the values with false(Useless to retrieve them from DB anyway).

userNamevalidityMap.entrySet().removeIf(e -> !e.getValue());

Golden rule is : Don't retrieve from DB if you are going to discard it!

Related