gpt4 book ai didi

java - 尝试在 forEach 方法中返回某些内容时,Void 方法无法返回值错误

转载 作者:行者123 更新时间:2023-11-29 07:27:44 27 4
gpt4 key购买 nike

我有一个片段如下

private String getString() {
List<String> stringList = Arrays.asList("s1", "s2");
stringList.forEach(item ->
{
if (item.equals("s1"))
return item;
});
return null;
}

现在我在尝试返回项时遇到编译错误Void methods cannot return a value。我用谷歌搜索,不明白为什么会这样,也不知道这个问题的解决方案。如何在上面的 forEach 循环中返回项目

最佳答案

forEach是一个消费过程。传递给 forEach 方法的函数预计会产生副作用,这些副作用不会直接导致返回值,例如打印列表的内容,或做一些其他事情操作。

基本上,任何作为 Consumer 的函数或返回 void 的方法在这里都是公平的游戏。

由于您明确寻找一个值,您可以使用Stream#findAny()相反。

// You don't do anything with the result you want anyway,
// so I'm simply printing it out. You should determine what you need to do
// with the value you get back.

Optional<String> findResult = stringList().stream().findAny(v -> v.equals("s1"));
findResult.ifPresent(System.out::println);

关于java - 尝试在 forEach 方法中返回某些内容时,Void 方法无法返回值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48363547/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com