user9804521
user9804521

Reputation:

java stream with 2 filters conditions

I'm trying to Filter with 2 conditions a List using a Stream:

private List<String> filterResources(final List<Resource> resources, final String resourceType, final String propertyName) {
    List<String> result = resources.stream()
            .filter(resource -> resource.isResourceType(resourceType))
            .map(Resource::getValueMap)
            .map(valueMap -> valueMap.get(propertyName, StringUtils.EMPTY))
            .collect(Collectors.toList());
    return result.stream().filter(s -> !s.isEmpty()).collect(Collectors.toList());

I'd like not to create the result object, thanks in advance.

Upvotes: 4

Views: 541

Answers (1)

Eran
Eran

Reputation: 393771

There's no reason for two Stream pipelines. You can apply the second filter on the original Stream pipeline before the terminal operation:

private List<String> filterResources(final List<Resource> resources, final String resourceType, final String propertyName) {
    return resources.stream()
            .filter(resource -> resource.isResourceType(resourceType))
            .map(Resource::getValueMap)
            .map(valueMap -> valueMap.get(propertyName, StringUtils.EMPTY))
            .filter(s -> !s.isEmpty())
            .collect(Collectors.toList());
}

Upvotes: 9

Related Questions