Java 8 个流 - 将 UUID 列表转换为考虑 NULL 的字符串列表
Java 8 streams - convert List of UUID to List of String considering NULL
- 我想为字段
selectedResources
设置一个List<String>
。
getProtectionSet()
returns一个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 异常?
虽然您当前的代码不应该真正面对 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>
- 我想为字段
selectedResources
设置一个List<String>
。 getProtectionSet()
returns一个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 异常?
虽然您当前的代码不应该真正面对 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>