Search code examples
javalambdajava-8

Returning a value from a method within a lambda expression


I'm trying to figure out how to return a method value from a lambda expression:

public int findMissingNumber(Collection<Integer> ints) {
    Single<Integer> start = new Single<>(1);
    ints.stream().mapToInt(Integer::valueOf).parallel().forEach(i -> {
        if (i != start.setValue(start.getValue() + 1)) {
            //return here
        }
    });
    return -1;
}

However, it seems that using the return keyword in the lambda expression will explicitly return to the lambda function itself. Is there some type of way to break or force a return for the entire method?


Solution

  • Is there some type of way to break or force a return for the entire method?

    No. At least, not unless you throw an exception.

    Basically, that's not what forEach is meant for. You could write a method which accepted a function which would return null for "keep going" and non-null for "stop, and make this the result"... but that method isn't forEach.

    The fact that you're using a lambda expression is really incidental here. Imagine you were just calling forEach and passing in some argument - wouldn't it be really weird if that call made your findMissingNumber method return (without an exception), without the findMissingNumber method itself having the return statement?