Java Stream:如何将 Set 传递给 Stream.of() 并在每个 elemnt 上调用方法



>我有这样的旧式代码:

        if (setContainer.getSet() == null) {
            return null;
        }
        for (SetElement setElement : setContainer.getSet()){
            if ("SomeString".equals(SetElement.getCode())) {
                return  setElement.getValue();
            }
        }
        return null;

我已经试过了,但它没有检查 Set 是否为空:

setContainer.getSet()
                    .stream()
                    .filter(setValue ->  "SomeValue".equals(setElement.getCode()))
                    .map(SetElement::getValue)
                    .findAny()
                    .orElse(null) ;

据我了解,我应该使用Stream.of()但是我不明白如何执行上述代码,因为它总是返回Optional<Set<SetElement>>

您可以使用

Optional.ofNullable来实现此目的:

return Optional.ofNullable(setContainer.getSet())
    .flatMap(set -> set.stream()
        .filter(e ->  "SomeValue".equals(e.getCode()))
        .map(SetElement::getValue)
        .findAny())
    .orElse(null);

当您的现有工具工作正常时,无需尝试应用新工具。因此,如果您需要空检查,请继续使用 if .

 set = setContainer.getSet();
 if(set == null) {
    return null;
 } else {
    return mapAndFilter(set);
 }

或者,使用三元运算符:

 Set<T> set = setContainer.getSet();
 return set == null ? null : mapAndFilter(set);

现在,您可以干净地实现mapAndFilter(),接受保证不为 null 的Map<T>,并返回 Map<U> 。使用流实现mapAndFilter()可能是有意义的。

引入Optional只会给代码添加不必要的对象和不必要的混乱。

也就是说,永远不要传递 null 是更好的风格,所以如果你可以增强你的setContainer,让它永远不会返回 null(也许它可以返回一个空集?(,那就更好了。

使setContainer供应Optional<Set<T>>可能是一个很好的折衷方案。但即便如此,传统技术可能比函数语法更可取:

 Optional<Set<T>> maybeSet = setContainer.getSet();
 return maybeSet.isPresent() ? mapAndFilter(maybeSet.get()) : null;
 // vs
 return maybeSet.isPresent() ? mapAndFilter(maybeSet.get()) : Optional.empty();
 // vs
 return maybeSet.map(mapAndFilterFunction); // might return empty Optional
 // vs
 return maybeSet.map(mapAndFilterFunction).orElse(null); // might return null;

在这些mapAndFilter()中是一种方法。 mapAndFilterFunction是定义为Function<Set<T>,Set<U>> mapAndFilterFunction = s -> { ... };Function

最新更新