Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get second occurrence of element from Java array

Tags:

java

arrays

I currently have a program that works on an array by using a for loop to iterate through the array with an embedded if statement that matches the element in the array to the one I'm looking for. I need to modify this so that it will find the second occurrence of the same element. Ideas on how to do this?

  String[] myStringArray = {"a", "b", "c", "a", "d", "e", "f"};

  for(int i=0; i<myStringArray.length; i++) {
       if(myStringArray[i].equalsIgnoreCase("a") {
            //do something
       }
  }

As noted, this will find the first a and I will do work on it, however the second a needs to be acted upon also.

like image 671
GregH Avatar asked Jun 14 '26 18:06

GregH


1 Answers

Use a counter.

String[] myStringArray = {"a","b","c","a","d","e","f"};

int occurrences = 0;

for(int i=0; i<myStringArray.length;i++{
     if(myStringArray[i].equalsIgnoreCase("a"){
          occurrences++;
          if(occurrences == 2) {
              // Do something
          }
     }
}
like image 154
Ayrton Massey Avatar answered Jun 16 '26 08:06

Ayrton Massey