foreach java 返回,在java中从lambda forEach()返回

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 playersOfTeam = new ArrayList();

for (Player player : players) {

if (player.getTeam().equals(teamName)) {

playersOfTeam.add(player);

}

}

With 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

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

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

解决方案

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

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

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值