Search code examples
javajava-8java-streamskip

Can we skip in Java8 Streams


I have a for loop which iterates across the employeeId list. In each iteration it calls a service to see if it has any values, if we get any values for an id then we need to skip all the remaining iteration. I have done that by using traditional for loop like as shopn below

for(int i=0; i<employeeIdLists.length; i++) {
    userDetails = someService.getUserId(employeeIdLists.get(i));
    if(userDetails != null) {
        i = employeeIdLists.length; // skip rest of the iteration
    }
}

I would like to know if I can do the similar one using Java Streams. I tried some but this is not meeting the expectations

employeeIdLists.stream()
.map(id -> someService.getUserId(id))
.filter(userDetails -> userDetails!=null)
.collect(Collectors.toList());

Solution

  • Yes, you do that with findAny() or findFirst(), which would stop the pipeline the first time a value is found (after the filter, in your case):

    userDetails = employeeIdLists.streams()
        .map(id -> someService.getUserId(id))
        .filter(userDetails -> userDetails!=null)
        .findAny()
        .orElse(null); //null if all values were null
    

    In this pipeline, userDetails will be set to a value that did not get a null result from the service, and the pipeline will be stopped as soon as such value is found.