我正在為帖子編寫代碼,但我在驗證中遇到了一些問題。getDocumentIds 是一個整數列表,我需要遍歷該列表并檢查該特定 id 是否有效。我已經嘗試使用下面的代碼,但是,當我傳遞值列表時,它只取第一個值。它沒有采用第一個值之后的值。 Document document= Optional.ofNullable(repositoryService.findById(Document.class, memberNoteResource.getDocumentIds().stream() .iterator().next())).orElse(null); if (document == null) { throw new ApiException(ApiErrorCode.DEFAULT_400, "Save unsuccessful document id is not part of member note"); }預期的結果是,我必須檢查所有傳遞的“getDocumentIds”,如果某些 id 不存在,那么我必須拋出一個錯誤
2 回答

一只甜甜圈
TA貢獻1836條經驗 獲得超5個贊
getDocumentIds是一個整數列表,我需要遍歷該列表并檢查該特定 id 是否有效。
您可以使用anyMatch來驗證是否id存在任何文檔(假設返回值null)。
if(memberNoteResource.getDocumentIds()
.stream()
.anyMatch((id)-> repositoryService.findById(Document.class,id) == null)) {
throw new ApiException(ApiErrorCode.DEFAULT_400,
"Save unsuccessful document id is not part of member note");
}

當年話下
TA貢獻1890條經驗 獲得超9個贊
我想你想要的是類似的東西
memberNoteResource.getDocumentIds().stream()
.map((id)-> {
repositoryService.findById(Document.class, id);
}).map(Optional::ofNullable);
然后你可以進一步用 .filter() 鏈接它來做更多的檢查。
添加回答
舉報
0/150
提交
取消