我正在尝试迭代元素列表的列表以测试给定条件。 虽然 Java 7 可以实现这一点,但我很想知道如何使用 Stream API 在 Java 8 中实现这一点。
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
public class Main2 {
static String[] positionsThatWillBeCovered = new String[]{"RB", "LB", "MD"};
static String[] positionsThatWillNotBeCovered = new String[]{"RB", "LB", "MD", "GK"};
public static void main(String[] args) {
Position p1 = new Position("RB");
Position p2 = new Position("LB");
Position p3 = new Position("MD");
Player alves = new Player(Arrays.asList(p1, p2));
Player alba = new Player(Arrays.asList(p2));
Player xavi = new Player(Arrays.asList(p3));
Team team = new Team(Arrays.asList(alves, alba, xavi));
//should print true
System.out.println(testAllPositionsAreCovered(team, positionsThatWillBeCovered));
//false
System.out.println(testAllPositionsAreCovered(team, positionsThatWillNotBeCovered));
}
private static boolean testAllPositionsAreCovered(Team team, String[] positionsToCover) {
for (String positionToCover : positionsToCover) { //"RB", "LB", "MD"
if (!isThePositionCoveredByAPlayer(team, positionToCover))
return false;
}
return true;
}
private static boolean isThePositionCoveredByAPlayer(Team team, String positionToCover) {
for (Player player : team.getPlayerList()) {
for (Position playerPosition : player.getPositions()) {
if(playerPosition.getPosition().equals(positionToCover))
return true;
}
}
return false;
}
}
class Team {
private List<Player> playerList;
Team(List<Player> playerList){
this.playerList = playerList;
}
public List<Player> getPlayerList() {
return playerList;
}
}
class Player {
private List<Position> positions;
Player(List<Position> positions){
this.positions = positions;
}
public List<Position> getPositions() {
return positions;
}
}
class Position {
private String position;
//some other fields...
public Position(String position) {
this.position = position;
}
public String getPosition() {
return position;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Position position1 = (Position) o;
return Objects.equals(position, position1.position);
}
@Override
public int hashCode() {
return Objects.hash(position);
}
}
一个团队包含一系列
Player
,一个Player
可以担任多个位置。
问题:
给定一支球队和一份位置列表,我需要知道列表中的每个位置是否至少可以由一名球员担任。
我有一个 Java 7 解决方案,它会遍历所有位置并检查是否至少有一名玩家可以参加比赛。
我对使用流的 Java 8 解决方案感兴趣。
使用 flatMap 将所有玩家的位置合并到一个流中:
public boolean testAllPositionsAreCovered(Team team,
String[] positions) {
Set<String> positionsOfTeams = team.getPlayers().stream()
.flatMap(p -> p.getPositions().stream())
.map(Position::getPosition)
.collect(Collectors.toSet());
return positionsOfTeams.containsAll(Arrays.asList(positions));
}