Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return the sum in an object ArrayList

Tags:

java

arraylist

Using a for each loop. how can I count the number of goals each player has and return that in the method goals() which is in the Team class? I know my current return statement is wrong I was unsure what to put there:

import java.util.ArrayList;

public class Team {

    private String teamName;
    private ArrayList<Player> list;
    private int maxSize = 16;

    public Team(String teamName) {
        this.teamName = teamName;
        this.list = new ArrayList<Player>();
    }

    public String getName() {

        return this.teamName;
    }

    public void addPlayer(Player player) {

        if (list.size() < this.maxSize) {
            this.list.add(player);
        }

    }

    public void printPlayers() {
        System.out.println(list);
    }

    public void setMaxSize(int maxSize) {

        this.maxSize = maxSize;
    }

    public int size() {

        return list.size();
    }

    public int goals(){

        for(Player goals : list){

        }
        return list;
    }
}

public class Player {

    private String playerName;
    private int goals;

    public Player(String playerName) {

        this.playerName = playerName;
    }

    public Player(String playerName, int goals) {

        this.playerName = playerName;
        this.goals = goals;
    }

    public String getName() {

        return this.playerName;
    }

    public int goals() {

        return this.goals;
    }

    public String toString() {

        return "Player: " + this.playerName + "," + goals;
    }
}

public class Main {
    public static void main(String[] args) {
        // test your code here
        Team barcelona = new Team("FC Barcelona");

        Player brian = new Player("Brian");
        Player pekka = new Player("Pekka", 39);
        barcelona.addPlayer(brian);
        barcelona.addPlayer(pekka);
        barcelona.addPlayer(new Player("Mikael", 1)); // works similarly as the above

        System.out.println("Total goals: " + barcelona.goals());
    }
}
like image 609
Noah Kettler Avatar asked Dec 29 '25 08:12

Noah Kettler


2 Answers

I think you're looking for something like

public int goals(){
    int total = 0;
    for(Player p : list){ // for each Player p in list         
       total += p.goals();
    }       
    return total;
}

Add the number of each Player's goals to the total and then return the total.

like image 198
Elliott Frisch Avatar answered Dec 31 '25 21:12

Elliott Frisch


return list.stream().mapToInt(Player::goals).sum();
like image 40
Don Bottstein Avatar answered Dec 31 '25 22:12

Don Bottstein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!