sbdayhfd
sbdayhfd

Reputation: 11

How to sum using stream() by a certain type of variable

I'm trying to sum all the points from the same team and return a list of strings (team : totalPoints)

public class Player {
    String name;
    int team;
    int points;
}

List <Player> player= new ArrayList<>();
player.add(new Player("Michael",1,10)); 
player.add(new Player("Mike",2,15));
player.add(new Player("Tom",1,7));  
player.add(new Player("Marty",2,9));

I wanted to receive a List<String>, with: "1 : 17" , "2 : 24"

Upvotes: 1

Views: 67

Answers (1)

Kartik
Kartik

Reputation: 7917

You could use, Collectors.groupingBy with a downstream Collectors.summingInt as :

List<String> result = player.stream()
        .collect(Collectors.groupingBy(Player::getTeam,
                Collectors.summingInt(Player::getPoints)))
        .entrySet().stream()
        .map(e -> e.getKey() + " : " + e.getValue())
        .collect(Collectors.toList());

Upvotes: 3

Related Questions