最佳答案
我试图将一些 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()
方法返回?