Get arraylist index using property of contained object in java

I have an Object Type list. That I have one property String idNum. Now I want to get the index of the object in the list by passing idNum.

List<Object1> objList=new ArrayList<Object1>();

I do not know how to give objList.indexOf(// Don't know how to give here);

Is it possible to do this without repeating the list. I want to use only the method indexOf().

+4
source share
3 answers

Write a little helper method.

 private int getIndexByProperty(String yourString) {
        for (int i = 0; i < objList.size(); i++) {
            if (object1 !=null && object1.getIdNum().equals(yourString)) {
                return i;
            }
        }
        return -1;// not there is list
    }

Remember to return -1 if not found.

+5
source

You cannot do this with indexOf. Instead, all objects in the list should inherit from a common interface - for example,

interface HasIdNum {
    String getIdNum();
}

List<HasIdNum>, , id, :

for (HasIdNum hid: objList) {
   if (hid.getIdNum().equals(idNumToFind) {
       return hid;
   }
}
return null;

, :

for (int i=0;i<objList.size();i++) {
   HasIdNum hid = objList.get(i);
   if (hid.getIdNum().equals(idNumToFind) {
       return i;
   }
}
return -1;

, , .

+2

equals ( hashCode) Object1 idNum, List.indexOf,

int i = objList.indexOf(new Object(idNum));

    final String idNum = "1";
    int i = list.indexOf(new Object() {
        public boolean equals(Object obj) {
            return ((X)obj).idNum.equals(idNum);
        }
    });
+2

All Articles