Reputation:
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
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