Java 8流 - 考虑到NULL,将UUID列表转换为String列表。

问题描述 投票:0回答:1
  • 我想设置一个 List<String> 到外地 selectedResources.
  • getProtectionSet() 返回一个 List<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-8 java-stream optional
1个回答
4
投票

虽然你不应该真正面对一个 NullPointerException 以你目前的代码,仍然有可能得到一个 NoSuchElementException 用于进行 get 关于 Optional 而不确认是否存在。

你应该使用 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>
© www.soinside.com 2019 - 2024. All rights reserved.