Home » Java » How do I compare strings held in an object which are held in an ArrayList and then add the value of those strings(if they are equal to one another)

How do I compare strings held in an object which are held in an ArrayList and then add the value of those strings(if they are equal to one another)

Posted by: admin August 11, 2018 Leave a comment

Questions:

How do I compare strings held in an object which are held in an ArrayList and then add the value of those strings(if they are equal to one another)?

I understand how to check if StringX == StringY or StringX.equals(StringY), but I fail to understand to compare strings in an ArrayList, much less how to add the value of doubles held in the String’s object(only if that string is equal).

Example
class BaseBallTeam has two attributes;

  • String teamMember e.g. Kat
  • Double homeRuns e.g. 2.0

I want to add up all the homeRuns(double) made by all the Kats(string). As well as all the homeRuns(double) made by all the mikes etc.

Heres my code:

ArrayList<BaseBallTeam> list = new ArrayList<>();
double totalRuns = 0;
for(int i = 0; i<list.size();i++){
   for(int j = 1; j<list.size();j++){        
    if(list.get(i).getTeamMember().equals(list.get(j).getTeamMember())){
       totalRuns += list.get(j).getHomeRuns() +list.get(i).getHomeRuns();
       System.out.println("Amount of " + list.get(i).getTeamMember() + "s hit " + totalRuns"home runs);
   }
}                   

My code provides all the team members cumulative frequency rather then adding up the two individual scores

Answers: