簡體   English   中英

將 stream 中的所有子集加入 Java optionals

[英]Joining all subsets within a stream in Java optionals

這是原始代碼:

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

我想將所有內容包裝在 Optional 中以避免 null 指針和所有指針。 如果學生不存在或 statutesSet 不存在。

我有的:

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);

這樣的事情有可能嗎? 我想避免在此鏈中進行 null 檢查,如果有任何 null 也只返回一個簡單的 null 而不是獲取異常。

通常我認為合乎邏輯的是使用這里描述的 flatMap但在這種情況下它似乎不正確,因為 Optional flatmap 返回一個 Optional。

這是一個簡單的方法:

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());

但是,它不會產生 null 集合。 Collections 永遠不應該是 null,只是空的。 我會推薦這種方法。 使用Optional object 的全部意義在於,您永遠不必處理 null 值。

Collection::stream不返回Optional ,所以你不應該在這里使用flatMap 您應該繼續使用可選的map

.map(Collection::stream)給你一個Optional<Stream<Statute>> 您似乎正在嘗試調用流的map並對此進行collect方法。 但是您需要先調用Optional.map才能執行此操作。

如果registration可以是 null,您還應該使用Optional.ofNullable

Set<StatuteType> statuteTypes = Optional.ofNullable(registration)
    .map(Registration_Base::getStudent)
    .map(student -> student.getStudentStatutesSet())
    .map(Collection::stream)
    .map(x -> // Optional.map
        x.map(StudentStatute_Base::getType) // Stream.map
            .filter(Objects::nonNull) // I assume you want to filter out the statute types which are null?
            .collect(Collectors.toSet())
    )
    .orElse(null);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM