Max value from list of list in Java

Adelmo Junior :

I'm trying to get the highest value by applying a filter

I have an object that contains a team object and a list of cards. so I need to get the highest value from the card list in the card weight attribute, where the team is A, and return the player.

public class Player {
  private String name;
  private List<Card> cards;
  private Team team;
  // getters and setters
}

public class Team {
  private int id;
  private int points;
  // getters and setters
}

public class Card {
  private int weightCard;
  // getters and setters
}

the code that I was trying to execute

int maxPointsTeamA = players
    .stream()
    .filter( x -> x.getTeam().equals(teamA))
    .map(n -> n.getCards()
    .stream()
    .map( c -> c.getWeigthCard()).max(Comparator.naturalOrder()));

players is a list of players (4 players)

error:

Type mismatch: cannot convert from Stream<Object> to int

help me please, it's for academic work

rzwitserloot :

Replace both of your map calls to mapToInt, for starters. You then do not need the Comparator.naturalOrder().

Secondly, your first map call contains this lambda:

n -> n.getCards().stream().map(c -> c.getWeightCard()).

That turns a single 'n', whatever that might be, into a stream of whatever weightcard returns (which is not code you pasted). The point of map is to turn one thing into one other thing, not a stream of things. You can use flatmap for that instead, so presumably, first flatMap to a stream of cards, then map that to an int via the weightcard function, and then you can max.

Putting it all together:

int maxPointsTeamA = players
            .stream()
            .filter(x -> x.getTeam().equals(teamA))
            .flatMap(n -> n.getCards().stream())
            .mapToInt(c -> c.getWeightCard())
            .max()
            .orElse(0);

EDIT: Ah, yes, I forgot max() returns an OptionalInt; fixed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=292136&siteId=1