List<String>
到外地 selectedResources
.getProtectionSet()
返回一个 List<ProtectionSet>
List<UUID> resourceIds
而这 List<UUID>
= List<String>
我想保存在selectedResources中。getProtectionSet()
是一个列表,但我想从第一个元素中获取值。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
用于进行 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>