在 Java 选项中加入流中的所有子集

Luc*_*cas 0 java optional

这是原始代码:

Set<StatuteType> statuteTypes = registration.getStudent().getStudentStatutesSet()
    .stream()
    .map(StudentStatute_Base::getType)
    .collect(Collectors.toSet());
Run Code Online (Sandbox Code Playgroud)

我想将所有内容都包装在 Optional 中以避免空指针和所有内容。如果学生不存在或法规集不存在。

我拥有的:

Set<StatuteType> statuteTypes = Optional.of(registration)
            .map(Registration_Base::getStudent)
            .map(student -> student.getStudentStatutesSet())
            .flatMap(Collection::stream)
            .map(StudentStatute_Base::getType)
            .collect(Collectors.toSet())
            .orElse(null);
Run Code Online (Sandbox Code Playgroud)

这样的事情有可能吗?我想避免在这个链中检查空值,如果有空值,也只返回一个简单的空值,而不是得到一个异常。

通常,我认为合乎逻辑的是使用此处描述flatMap,但在这种情况下似乎不正确,因为 Optional flatmap 返回一个 Optional。

Geo*_*rge 5

这是一个简单的方法:

Set<StatuteType> statuteTypes = Optional.ofNullable(registration)
    .map(Registration_Base::getStudent)
    .map(student -> student.getStudentStatutesSet())
    .map(Collection::stream)
    .orElseGet(Stream::empty)    // Exit Optional, enter stream
    .map(StudentStatute_Base::getType)
    .collect(Collectors.toSet());
Run Code Online (Sandbox Code Playgroud)

但是,它不会导致空集。集合永远不应该为空,只能为空。我会推荐这种方法。使用Optional对象的全部意义在于您永远不必处理空值。