在java中从lambda forEach()返回 [英] Return from lambda forEach() in java

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

问题描述

我正在尝试将一些for-each循环更改为lambda forEach() -methods以发现lambda表达式的可能性。以下似乎是可能的:

I am trying to change some for-each loops to lambda forEach()-methods to discover the possibilities of lambda expressions. The followong seems to be possible:

ArrayList<Player> playersOfTeam = new ArrayList<Player>();      
for (Player player : players) {
    if (player.getTeam().equals(teamName)) {
        playersOfTeam.add(player);
    }
}

使用lambda forEach()

players.forEach(player->{if (player.getTeam().equals(teamName)) {playersOfTeam.add(player);}});

但下一个工作不起作用:

But the next one doesen't work:

for (Player player : players) {
    if (player.getName().contains(name)) {
        return player;
    }
}

with lambda

with lambda

players.forEach(player->{if (player.getName().contains(name)) {return player;}});

最后一行的语法是否有问题或者无法从<$ c返回$ c> forEach()方法?

Is there something wrong in the syntax of the last line or is it impossible to return from forEach() method?

推荐答案

返回从lambda表达式而不是contains方法返回。而不是 forEach 你需要过滤流:

The return there is returning from the lambda expression rather than from the containing method. Instead of forEach you need to filter the stream:

players.stream().filter(player -> player.getName().contains(name))
       .findFirst().orElse(null);

此处过滤器将流限制为这些项与谓词匹配,然后 findFirst 然后返回带有第一个匹配条目的可选

Here filter restricts the stream to those items that match the predicate, and findFirst then returns an Optional with the first matching entry.

这看起来效率低于for-loop方法,但实际上 findFirst()可以短路 - 它不会产生整个过滤后的流然后从中提取一个元素,而不是只需要过滤所需的元素就可以找到第一个匹配的元素。您也可以使用 findAny()而不是 findFirst()如果您不一定关心第一个来自(有序)流的匹配玩家,但只是任何匹配的项目。当涉及并行性时,这可以提高效率。

This looks less efficient than the for-loop approach, but in fact findFirst() can short-circuit - it doesn't generate the entire filtered stream and then extract one element from it, rather it filters only as many elements as it needs to in order to find the first matching one. You could also use findAny() instead of findFirst() if you don't necessarily care about getting the first matching player from the (ordered) stream but simply any matching item. This allows for better efficiency when there's parallelism involved.

这篇关于在java中从lambda forEach()返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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