Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of an arraylist using property of an contained object in java [duplicate]

I'm having an list of Object type. In that I have one String property idNum. Now I want to get the index of the object in the list by passing the idNum.

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

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

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

like image 374
Monicka Akilan Avatar asked Dec 30 '13 09:12

Monicka Akilan


2 Answers

Implement equals (and hashCode) in Object1 class based on idNum field, then you use List.indexOf like this

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

or make a special class for seaching

    final String idNum = "1";
    int i = list.indexOf(new Object() {
        public boolean equals(Object obj) {
            return ((X)obj).idNum.equals(idNum);
        }
    });
like image 154
Evgeniy Dorofeev Avatar answered Sep 24 '22 11:09

Evgeniy Dorofeev


Write a small 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
    }

Do not forget to return -1 if not found.

like image 42
Suresh Atta Avatar answered Sep 21 '22 11:09

Suresh Atta