Get index of objects in Java list

I have a list of strings in my (Android) Java program, and I need to get the index of the object in the list. The problem is that I can find documentation on how to find the first and last index of an object. What if I have 3 or more than one object in my list? How can I find each index?

Thank!

+3
source share
3 answers

You need to do a brute force search:

  static <T> List<Integer> indexesOf(List<T> source, T target)
  {
     final List<Integer> indexes = new ArrayList<Integer>();
     for (int i = 0; i < source.size(); i++) {
       if (source.get(i).equals(target)) { indexes.add(i); }
     }
     return indexes;
  } 

, . / . , ( ), deathmarch O (n).

get(i) O (1) (ArrayList) O (n) (LinkedList), O (n 2). ArrayList, LinkedList .

+6

, ,

 ArrayList<String> obj = new ArrayList<String>();


 obj.add("Test Data"):  // fill the list with your data

 String dataToFind = "Hello";

 ArrayList<Integer> intArray = new ArrayList<Integer>();

 for(int i = 0 ; i<obj.size() ; i++)
 {
    if(obj.get(i).equals(dataToFind)) intArray.add(i);     
 } 

 now intArray would have contained all the index of matched element in the list
+2

An alternative brute force method that will also find all indices null:

static List<Integer> indexesOf(List<?> list, Object target) {
    final List<Integer> indexes = new ArrayList<Integer>();
    int offset = 0;
    for (int i = list.indexOf(target); i != -1; i = list.indexOf(target)) {
        indexes.add(i + offset);
        list = list.subList(i + 1, list.size());
        offset += i + 1;
    }
    return indexes;
}
+1
source

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


All Articles