Search code examples
javalistsearcharraylist

Search value in a java list by some of its fields


Good morning. Currently I have the following java class of which I have a list of identities:

@Getter
@AllArgsConstructor
@RegisterForReflection
@NoArgsConstructor
@Setter
public class Identity {

    private String type;
    private String id;
    @JsonIgnore
    private String account;
    private List<String> services;
    private List<String> roles;
}

Currently I have a List of Identity (List <Identity>) and I need to search within this list for some or all of its parameters, that is, I can have the following use cases for searching for an identity within the list:

 1. type && id;
 2. type && id && services; 
 3. type && id && services && roles;

How can I do in this case? I know that lists have methods like contains, but I don't know if they apply to partial searches like I want, what I want is that if it makes a match it returns the element


Solution

  • If I understand your question, you need something like this:

    public Identity findIdentity(List<Identity> identities, String type, String id, List<String> services, List<String> roles) {
        return identities.stream()
                .filter(identity -> isCorrectIdentity(type, id, services, roles, identity))
                .findFirst()
                .orElse(null);
    }
    
    private boolean isCorrectIdentity(String type, String id, List<String> services, List<String> roles, Identity identity) {
        return identity.getType().equals(type) && identity.getId().equals(id) &&
                (services == null || new HashSet<>(identity.getServices()).containsAll(services)) &&
                (roles == null || new HashSet<>(identity.getRoles()).containsAll(roles));
    }
    

    This will loop over your list, check element by element the type and id and if the services are defined it will check also with services and in the end if the roles are defined it will search by roles.

    Note: you can simplify the isCorrectIdentity by using multiple if elses or multiples methods.