我试图将一些for-each循环更改为lambda- forEach()
方法,以发现lambda表达式的可能性。以下似乎是可能的:
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);}});
但是下一个无效:
for (Player player : players) {
if (player.getName().contains(name)) {
return player;
}
}
带lambda
players.forEach(player->{if (player.getName().contains(name)) {return player;}});
最后一行的语法是否有问题,或者不可能从forEach()
方法中返回?