How to count recurring elements in String arrays in java?

String[] secretCodes = {"XXX","POP","XXX","FFF","POP","JIB","OWN","OOP","CCN"};

String[] options = {"XXX","POP,"FFF","JIB","OWN","OOP","CCN"};

How would I count how many times elements in secretCodes repeat?

For example I want it to say XXX = 2

3 Answers

  • 9 years ago

    You're counting the occurances of the strings in options that occur in secretCode, right?

    You can do that with a simple nested loops:

    int[] opCnt = new int[ options.length ];

    java.util.Arrays.fill( opCnt, 0 ); // init to 0

    for( int k=0; k<secretCode.length; k++ ) {

    ...for( int j=0; j<options.length; j++ ) {

    ......if( secretCode[k].equals( options[j] ) {





    This does, of course, assume that the strings in options are unique. However, if they are not then there is a simple relationship that can easily be determined.

  • 9 years ago

    I would use a some sort of Map (or hashmap or similar) to map each instance of String to and Integer object


    Map myMap<String, Integer>;

    if the String is found in the map, you increment the Integer

  • 9 years ago

    Read about java containers such as sets, hashtables, etc

Still have questions? Get answers by asking now.