Better way to find index of item from ArrayList<CustomObject>

Scorpion picture Scorpion · Nov 12, 2012 · Viewed 21.2k times · Source

First of all, please correct me If I am wrong. I want to find index of Item (i.e String value) from ArrayList<CustomType> without using For Loop.

POJO:

id;
name;

Code:

ArrayList<POJO> list = new ArrayList<POJO>;

//Lots of data added to these list...

Now I want to find the id of particular name from the arraylist without using below kind of for loop.

String id = null;
// TODO Auto-generated method stub
for (int i = 0; i < list.size(); i++) {
    if("ABCD".equalsIgnoreCase(list.get(i).getName())) {
        id = list.get(i).getId();
        break;
    }
}

Ideally I don't want to implement the For loop because in some cases i have 500+ data inside the List and to find index using a For loop is not a good way to do this.

Answer

Dan D. picture Dan D. · Nov 12, 2012

You can use list.indexOf(), but in order to make it work, you need to override equals and hasCode of your POJO.

By default, two objects will be considered equal if they have the same reference. You can overwrite equals to work for your case:

public boolean equals(Object o) {
  if (!(o instanceof POJO)) {
    return false;
  }
  POJO other = (POJO) o;
  return name.equalsIgnoreCase(other.getName());
}

Overridding equals would suggest you override hashCode. For example:

public int hashCode() {
  return name.hashCode();
}