You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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 result list: Instead of collecting mapped values first and spinning up a new stream to filter empty strings, we add the filter(s -> !s.isEmpty()) step right after the second map operation.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:14:31