How to iterate through a Stream of integers? and at thee mean time during the iteration I have to check it for some conditions

Jeeva D :

I am writing a code for post, but I am facing some issues in the validations.

getDocumentIds is a list of integers and what I need is to iterate through the list and check whether that particular id is valid or not.

I have tried with the below code but, when i pass the list of values it is taking only the first value. It is not taking the values after the first one.

    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");
    }

The expected result is, I have to check for all the "getDocumentIds" passed and if some id is not present then i have to throw an error

Naman :

getDocumentIds is a list of integers and what I need is to iterate through the list and check whether that particular id is valid or not.

You could use anyMatch to validate if, for any of the id, there is no document present(assuming return value 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");
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=79063&siteId=1