-2

I have an ArrayList of say, this object:

class Object() {
    String name;
    double price;
    int id;
}

I want to find the index of the ArrayList that contains the element where the name field is equal to a given string. For example:

public int findIndex(ArrayList<Object> list, String name) {
    for(Object o : list) {
        if (o.getName().equals(name) {
            //return index
        }
    }
}

What's a good way to return the index?

John
  • 59
  • 1
  • 6

2 Answers2

3

You can iterate the list with an indexed-for-loop:

for(int i = 0; i < list.size(); i++) { 
    if (list.get(i).getName().equals(name)) { 
        return i; 
    } 
} 
return -1;

Or simply use a counting variable when you want to use the for-each-loop:

int i = 0;
for(Object o : list) {
    if (o.getName().equals(name)) {
        return i;
    }
    i++;
}
return -1;

Or using Java-8 streams:

return IntStream.range(0, list.size())
    .filter(i -> list.get(i).getName().equals(name))
    .findFirst()
    .orElse(-1);

You see that I returned -1 when nothing was found. This is a common concept used throughout the java language.

Lino
  • 19,604
  • 6
  • 47
  • 65
-2

I think you can just do:

public int findIndex(ArrayList<Object> list, String name) {
    for(Object o : list) {
        if (o.getName().equals(name) {
            return list.indexOf(o);
        }
    }
    return -1;
}

(-1 is returned if nothing was found).

CrystalSpider
  • 377
  • 7
  • 16