Gayath_chandi
Gayath_chandi

Reputation: 61

Create a method for return set of Predicates

I have created 3 predicates that are used inside one method of this Service class. These are the 3 Predicates that are currently in one method. But when implementing this project it seems like these predicates are useable for other service methods as well.

Therefore is there any way to get these into a separate method and call that method when we want to get these predicates? The type of Predicate also needed to change. For that can I use generics like Predicate<T>?

Predicate<LocalRequestDTO> allFilter = request -> (!StringUtils.isBlank(request.getSuvc())
        && !StringUtils.isBlank(request.getSuffix()) && !StringUtils.isBlank(request.getSite()));
Predicate<LocalRequestDTO> suvcSuffixFilter = request -> (!StringUtils.isBlank(request.getSuvc())
        && !StringUtils.isBlank(request.getSuffix()) && StringUtils.isBlank(request.getSite()));
Predicate<LocalRequestDTO> suvcFilter = request -> (!StringUtils.isBlank(request.getSuvc())
        && StringUtils.isBlank(request.getSuffix()) && StringUtils.isBlank(request.getSite()));

Upvotes: 1

Views: 839

Answers (1)

Matt
Matt

Reputation: 13923

One option is to create a method that returns a Predicate:

private static Predicate<LocalRequestDTO> allFilter() {
    return request -> (!StringUtils.isBlank(request.getSuvc()) &&
            !StringUtils.isBlank(request.getSuffix()) &&
            !StringUtils.isBlank(request.getSite()));
}
List<LocalRequestDTO> allDto = dtos.stream()
        .filter(allFilter())
        .collect(Collectors.toList());

Another option is to define the Predicate as a constant:

private static final Predicate<LocalRequestDTO> SUVC_FILTER = request ->
        (!StringUtils.isBlank(request.getSuvc()) &&
                StringUtils.isBlank(request.getSuffix()) &&
                StringUtils.isBlank(request.getSite()));
List<LocalRequestDTO> suvcDto = dtos.stream()
        .filter(SUVC_FILTER)
        .collect(Collectors.toList());

Or you could just create a method that accepts a DTO and returns a boolean without using predicates at all as suggested by @Lino:

private static boolean doSuvcFilter(LocalRequestDTO request) {
    return !StringUtils.isBlank(request.getSuvc()) && 
            StringUtils.isBlank(request.getSuffix()) && 
            StringUtils.isBlank(request.getSite());
}
List<LocalRequestDTO> suvcDto = dtos.stream()
        .filter(ClassNameContainingMethod::doSuvcFilter)
        .collect(Collectors.toList());

Upvotes: 3

Related Questions