Другие уже дали хорошие ответы. Но вот ответ, который также генерирует для вас тестовые данные (с использованием потоков) и позволяет получить максимальный
Переопределить / определить метод toString () для Team:
class Team {
private int id;
private int points;
@Override
public boolean equals(Object otherTeam){
Team t = (Team) otherTeam;
return this.getId() == t.getId() ? true : false;
}
}
Решение: Я добавил комментарии в код, чтобы объяснить, как работает решение.
class Test{
//MAIN METHOD - START HERE !!!
public static void main(String [] args){
//Prepare test data.
List<Player> players = getTestData();
Player onePlayer = players.get(players.size()/2);//3rd player when list has 5 players.
List<Card> onePlayerCards = onePlayer.getCards();
Team teamA = new Team(onePlayer.getTeam().getId(), onePlayer.getTeam().getPoints());
//Test the max finder.
Integer max = getMax(players, teamA);
System.out.println("Expected max: " + onePlayerCards.get(onePlayerCards.size()-1).getWeightCard());
System.out.println("Actual max: " + max);
}
public static int getMax(List<Player> players, Team team){
//Replace this with method with any other method you'd like to test.
return getMax_byMasterJoe2(players, team);
}
public static int getMax_byMasterJoe2(List<Player> players, Team team){
Integer max = players
.stream()
//Extract player whose team is teamA.
.filter(player -> player.getTeam().equals(team))
//Get the cards of a player.
//.map() gives us Stream<List<Card>>. flatMap() gives us Stream<Card> which is what we need.
.flatMap(player -> player.getCards().stream())
//Get only the weights of each card of a player.
.mapToInt(Card::getWeightCard)
//Get maximum weight of a player's cards.
.max()
//If player has zero cards, then return 0.
.orElse(0);
return max;
}
public static List<Player> getTestData(){
List<Player> players = Stream
//Players numbers.
.of(1,2,3,4,5)
//Use player number to make player object.
.map(n -> new Player(
//Player name.
"player" + n,
//Generate n cards for n-th player. Ex. n=3 gives cards with weights 10, 20, 30.
IntStream.range(1, n+1).mapToObj(num -> new Card(num * 10)).collect(Collectors.toList()),
//Team.
new Team(n, n * 10)))
.collect(Collectors.toList());
//Remove all cards of last player for testing.
players.get(players.size()-1).getCards().clear();
return players;
}
}