【问题标题】:Java 8 streams - convert List of UUID to List of String considering NULLJava 8 流 - 考虑 NULL 将 UUID 列表转换为字符串列表
【发布时间】:2020-04-26 17:38:43
【问题描述】:
  • 我想为字段selectedResources 设置一个List<String>
  • getProtectionSet() 返回 List<ProtectionSet>
  • ProtectionSet 有一个字段 List<UUID> resourceIds 而这个 List<UUID> = List<String> 我想保存在 selectedResources 中。
  • getProtectionSet() 是一个列表,但我想从第一个获取值 元素
  • 我不想出现 NPE 异常
  • 当任何列表为空时,再往前走是没有意义的。
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 异常?

【问题讨论】:

    标签: java java-8 java-stream optional


    【解决方案1】:

    虽然您不应该用当前代码真正面对NullPointerException,但仍有可能在不确认存在的情况下在Optional 上执行NoSuchElementException 获得NoSuchElementException

    您应该提前几个阶段使用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>
    

    【讨论】:

    • 我猜.orElse(Collections.emptyList())可以省略。如果源为空,则调用 Optional::stream 返回一个空。
    • @Nikolas true,但仅限于 Java-9+
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    相关资源
    最近更新 更多