Warm tip: This article is reproduced from stackoverflow.com, please click
arraylist for-loop if-statement java jsp

Count same values in a row of an ArrayList

发布于 2020-04-11 22:31:05

I got an ArrayList which consist of 2 type of values: win & loss. I'm trying to count how many times in a row a win have occurred in the ArrayList. I have noget been able to complete the taske so far.

ArrayList <String> wins = new ArrayList<String>();
System.out.print(wins);
//[Won, Won, Won, Loss, Loss, Won, Won, Loss, Loss, Loss, Loss, Loss, Won, Won, Won, Won, Won, Loss]

String value = wins.get(0);

int maxValue=1;
int count = 1 ;

for (int i=1; i<wins.size(); i++){
     if(wins.get(i) == wins.get(i-1)){      
        count++;       
        if(count >= maxValue){
            maxValue = count;
            value = wins.get(i);
        }
    }
}

System.out.println(value + " : " + maxValue );
// Won : 1

The outcome is obviusly wrong as win have occurred 4 times in a row at some point in the ArrayList. Can anyone help me out with this one?

Questioner
egx
Viewed
51
NoDataFound 2020-02-02 22:37

You should try by using equals and not reference == equality:

if(wins.get(i) == wins.get(i-1)){  

Should be:

if(wins.get(i).equals(wins.get(i-1))) {  

Why this could work with String, given that constant are interned, this is not always the case.

Last but not least, you must reset your count when the equality mismatch!

As in:

for (int i=1; i<wins.size(); i++){
  String current = wins.get(i);
  if (current.equals(wins.get(i-1))) {      
    count++;       
    if(count >= maxValue){
      maxValue = count;
      value = current;
    }
  } else {
    count = 0;
  }
}

Note that you probably don't need value at all.