我正在尝试在可以为 null
的列表上应用流,因为它正在调用存储库方法,如果它不为 null,我想从中获取第一个元素并比较它的一个带有请求值的参数。
Optional.ofNullable(placementRepository.findAllByAccountId(accountId))
.orElseGet(Collections::emptyList)
.stream()
.filter(Objects::nonNull)
.findFirst()
.get()
.getPlacementDate()
.isAfter(placementRequest.getPlacementDate())
目前,如果列表本身为 null
,则它在 .get
失败,尽管我使用 nonNull 进行了过滤。如果列表不为空,我想流式传输列表并获取第一个元素并将其参数与其他值进行比较。我尝试使用其他替代过滤器,但没有成功
最佳答案
I want stream the list if the list is not null and get the first element and compare its parameter against other value.
你没有想到repository返回的List中有空元素或者null元素的情况。您必须选择一个默认值或仅当存在可选值时才执行日期比较。
例如使用默认日期值:
final LocalDate defaultDateValue = ...;
Optional.ofNullable(placementRepository.findAllByAccountId(accountId))
.flatMapping(l -> l.stream()
.filter(Objects::nonNull)
.findFirst()
.mapping(o -> o.getPlacementDate())
)
.orElse(defaultDateValue)
.isAfter(placementRequest.getPlacementDate())
有条件的处理:
Optional<LocalDate> opt =
Optional.ofNullable(placementRepository.findAllByAccountId(accountId))
.flatMapping(l -> l.stream()
.filter(Objects::nonNull)
.findFirst()
.mapping(o -> o.getPlacementDate())
)
if (opt.isPresent()){
boolean isAfter = opt.get().isAfter(placementRequest.getPlacementDate());
// ...
}
关于java - Stream if not null 并获取第一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54381835/