Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 314
Scorpion Avatar asked Nov 12 '12 09:11

Scorpion


People also ask

How do you find the index of an ArrayList item?

The index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().

How will you get the index of an object in a list?

Use List Comprehension and the enumerate() Function to Get the Indices of All Occurrences of an Item in A List.

How do you retrieve a specific item from an ArrayList object?

An element can be retrieved from the ArrayList in Java by using the java. util. ArrayList. get() method.

How do I get the index of an ArrayList in Kotlin?

The ArrayList class contains the indexOf() method, which returns the index of the first occurrence of a specified element in the array list, or -1 , if the element is not contained in the list.


2 Answers

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();
}
like image 65
Dan D. Avatar answered Nov 15 '22 20:11

Dan D.


Finding element in this way where complexity would be give you BIG-O (n). I think if you Map that would gives you better result.

HashMap would be better choice. - Where Complexity would be O(1).

like image 22
Subhrajyoti Majumder Avatar answered Nov 15 '22 20:11

Subhrajyoti Majumder