Sauron
Sauron

Reputation: 6657

Return all indices of matching elements in array

I have an array as: ["Front", "Front", "Back", "Back", "Side", Side]

What I need to do is return the indices for all matching occurrences of a particular string. For example, if inputting: "Front" it should return [0,1], input "Side", should return [4,5] and "Back" would return [2,3]

How can this be accomplished in Java efficiently?

Upvotes: 0

Views: 1398

Answers (1)

Anptk
Anptk

Reputation: 1123

Try this

    String inPut="Side";

    String data [] = {"Front", "Front", "Back", "Back", "Side", "Side"};

    ArrayList positions=new ArrayList();

    for(int i=0;i<data.length;i++)
    {
        if(inPut.equals(data[i]))
        {
            positions.add(i);
        }
    }

    System.out.println(positions);
} 

output

[4, 5]

Try with changed inputs

Upvotes: 1

Related Questions