Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 516
marcoguastalli Avatar asked Jan 03 '23 09:01

marcoguastalli


1 Answers

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());
}
like image 123
Eran Avatar answered Jan 11 '23 21:01

Eran