流水线计算时如何应用IF逻辑?

How to apply IF logic during stream pipeline calculation?

我有这样的代码。不过有点难看

Set<String> strings= new HashSet(Arrays.asList("str1", "str2", "str3" ));
Optional.of(strings.stream()
                .filter(myMap::containsKey)
                .collect(Collectors.toMap(Function.identity(), myMap::get)))
                .map(stringListMap -> stringListMap.isEmpty() ? null : stringListMap)
                .orElse(myMap)
                .entrySet()
                .stream()
                .flatMap(...)
                ...  

有没有办法避免在管道中间收集?

我认为更命令的解决方案在这里实际上更具可读性。

Map<String, Object> actualMap = myMap; // equiv. to your .orElse(myMap)
if (myMap.keySet().stream().anyMatch(strings::contains)) {
    actualMap = strings.stream().collect(Collectors.toMap(Function.identity(), myMap::get));
}
actualMap.entrySet().stream()
    .flatMap(...)

Java 是一种很好的语言,因为它可以让您在应用函数式想法时务实。不要觉得你必须一直使用它们。

我没有在这里添加太多 - 与迈克尔的回答非常相似。但这避免了从 myMapstrings.

中创建流
Map<String, Object> mappedValues = strings.stream()
     .filter(myMap::containsKey)
     .collect(Collectors.toMap(Function.identity(), myMap::get)));

(mappedValues.isEmpty()
    ? myMap
    : mappedValues).entrySet()
            .stream()
            .flatMap(...)

这是一种迟到的答案,但以下解决方案不使用 Optional,并且如果 myMap 中不存在来自 strings 的键,则不会创建映射,代价是重复 运行 较小 strings 集上的流:

(strings.stream().anyMatch(myMap::containsKey)
    ? strings.stream()
             .filter(myMap::containsKey)
             .collect(Collectors.toMap(k -> k, myMap::get))
    : myMap
)
.entrySet().stream()
           .flatMap()