如何使用Java Stream实现双条件过滤List且避免创建中间集合
Optimizing Java Stream Pipeline to Avoid Intermediate Collections
Great question! You can eliminate the intermediate result list by chaining all your stream operations together in a single pipeline. This keeps your code cleaner and avoids unnecessary memory overhead from storing a temporary collection.
Here's the refactored version:
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()) // Move this filter directly into the original pipeline .collect(Collectors.toList()); }
Key Changes Explained:
- Removed the intermediate
resultlist: Instead of collecting mapped values first and spinning up a new stream to filter empty strings, we add thefilter(s -> !s.isEmpty())step right after the secondmapoperation. - Preserved lazy evaluation: Stream operations are lazy, so adding the filter earlier means we never process or store empty string values at all—this is more efficient than collecting them first just to discard them later.
- Simplified code flow: The entire logic now runs in a single pass over the input list, making the code easier to follow and maintain.
If you prefer a more concise version (without sacrificing readability), you can combine the two map operations into one:
private List<String> filterResources(final List<Resource> resources, final String resourceType, final String propertyName) { return resources.stream() .filter(resource -> resource.isResourceType(resourceType)) .map(resource -> resource.getValueMap().get(propertyName, StringUtils.EMPTY)) .filter(s -> !s.isEmpty()) .collect(Collectors.toList()); }
Both versions achieve your goal of avoiding the intermediate collection while retaining exactly the same functionality.
内容的提问来源于stack exchange,提问作者user9804521
相关产品推荐
相关产品推荐

