Finding an index of duplicate values โ€‹โ€‹in an ArrayList

I have an ArrayList that contains duplicate values โ€‹โ€‹at diff diff index. for example {"Indian","American","Chinese","Australian","Indian","Russian","Indian"} since u can see that the value - "Indian" exists in the index - 0 , 4 and 6 .

I need to know all these indexes where "Indian" exists and create an array. 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 the duplicate is repeated, getting the size of the indexes (ArrayList) but when I check the values. Its one value in the whole index, as in the: indexOf() method, it always brings the index of the first value that it finds in the array.

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

+6
source share
2 answers

You need to know which index in the array you are currently in, and not the first index where it should be found. To track this, 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 found this value, so you can add i to the list of indexes.

+2
source

This is a situation where an index-based loop is more appropriate than an improved one for the loop you are using, since what you need to capture is the index.

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

 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 and not an array, then, of course, similar code will work, but using list.get(i) instead of category[i] .

+2
source

Source: https://habr.com/ru/post/886466/


All Articles