7

I have an ArrayList which contains duplicate values at diff diff index. for example {"Indian","American","Chinese","Australian","Indian","Russian","Indian"} as u can see the value - "Indian" exists at index - 0, 4 & 6.

I need to know all these indexes where "Indian" exists and create an arrayList of that. Here is my code:

public void filter(){


    categoryArray = Arrays.asList(category);

    for(String k : category){
        //Log.v("filter", filterTerm);
        if(k.equals(filterTerm.toLowerCase()))
        {               
            int p = categoryArray.indexOf(k);                   
            Log.v("index of categArr", ""+p);
            String id = Integer.toString(p);
            indexes.add(id);


        }// end of if
    }// end of for

Here I get how many times duplicate occurs by getting the size of indexes(ArrayList) but when I check the values . Its one value at all index since in the method : indexOf() it always brings the index of first value that it finds in the Array.

So if duplicate exists at index - 2,5,7 I get the array size of index as 3. But the values are {2,2,2,};

2 Answers 2

3

This is a situation where an index-based for loop is more appropriate than enhanced for loop that you're using, as what you need to grab is the index.

You can base all your work on the original array rather than converting it to a list, and I suspect you were going for case-insensitive match.

public void filter(){
    for(int i=0; i<category.length; i++){
        if(category[i].equalsIgnoreCase(filterTerm))
        {               
            String id = Integer.toString(i);
            indexes.add(id);
        }
    }
}

If you have an ArrayList rather than an array, of course similar code will work, but using list.get(i) instead of category[i].

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, this solution is slightly more efficient, as the iterator created implicitly by the original for loop would maintain its own separate index.
could you explain what is filterTerm in this answer ??
2

You need to know which index in the array you are currently at, not the first index where it is to be found. To keep track of that, put

int i = 0;

before the loop, and at the very end of the loop put

i++;

Then the variable i tells you where you have found the value, so you can add i to the indexes list.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.