Java 8 个流 - 将 UUID 列表转换为考虑 NULL 的字符串列表

Java 8 streams - convert List of UUID to List of String considering NULL

private Mono<Protection> addProt(Protection protection) {
...
...
    MyClass.builder()
    .fieldA(...)
    .fieldB(...)
    .selectedResources(  //-->List<String> is expected
                       protection.getProtectionSet().stream() //List<ProtectionSet>
                                  .filter(Objects::nonNull)
                                  .findFirst()
                                  .map(ProtectionSet::getResourceIds) //List<UUID>
                                  .get()
                                  .map(UUID::toString)
                                  .orElse(null))
    .fieldD(...)

如何编写流以避免 NPE 异常?

虽然您当前的代码不应该真正面对 NullPointerException,但仍然有可能获得 NoSuchElementException 以在 Optional 上执行 get 而无需确认存在。

你应该使用 orElse 提前几个阶段,因为我理解这个问题,这样你 map 找到第一个元素并仅流式传输它的元素(如果可用):

protection.getProtectionSet().stream() //List<ProtectionSet>
        .filter(Objects::nonNull)
        .findFirst() // first 'ProtectionSet'
        .map(p -> p.getResourceIds()) // Optional<List<UUID>> from that 
        .orElse(Collections.emptyList()) // here if no such element is found
        .stream()
        .map(UUID::toString) // map in later stages
        .collect(Collectors.toList()) // collect to List<String>