从 java 中的 lambda forEach() 返回
2022-08-31 08:58:23
我正在尝试将一些 for-each 循环更改为 lambda 方法,以发现 lambda 表达式的可能性。以下情况似乎是可能的:forEach()
ArrayList<Player> playersOfTeam = new ArrayList<Player>();
for (Player player : players) {
if (player.getTeam().equals(teamName)) {
playersOfTeam.add(player);
}
}
使用λforEach()
players.forEach(player->{if (player.getTeam().equals(teamName)) {playersOfTeam.add(player);}});
但是下一个不起作用:
for (Player player : players) {
if (player.getName().contains(name)) {
return player;
}
}
与λ
players.forEach(player->{if (player.getName().contains(name)) {return player;}});
最后一行的语法是否有问题,或者是否无法从方法返回?forEach()