从lambda表达式中的方法返回值 [英] Returning a value from a method within a lambda expression

查看:1230
本文介绍了从lambda表达式中的方法返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试图弄清楚如何从lambda表达式返回一个方法值:

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

但是,似乎使用返回关键字将显式返回lambda函数本身。有没有某种方法可以打破或强制整个方法返回?

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?

推荐答案


是有什么类型的方法来打破或强制整个方法的回报?

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.

基本上,这不是 forEach 的意思。您可以编写一个接受函数的方法,该函数将返回 null 表示保持运行而非空表示停止,并使其成为结果......但是方法不是 forEach

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.

你正在使用lambda的事实表达在这里是偶然的。想象一下,你只是在调用 forEach 并传入一些参数 - 如果那个调用你的那么它不会真的很奇怪findMissingNumber 方法返回(没有异常),没有 findMissingNumber 方法本身有return语句?

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?

这篇关于从lambda表达式中的方法返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆