Find indexOf of an object in custom list using one attribute

Viewed 1262

So, I have a custom class, and an arraylist of that class type. Now, I want to retrieve the index of an object in this arraylist using only an ID that is available to me among the other attributes that make up an object of that class.

Saw a few examples online, but I'm kinda confused, they're overriding hashCode() and equals(), and in equals() they're checking all the attributes, I just want to check with the ID value, since for every object ID is unique.

public class MyClass {
    private String ID;
    private String name;
    private String userName;
    private String position;

    // Constructors and getters and setters
}

So, what I want is, for say this piece of code:

List<MyClass> list=new ArrayList<>();
//Values are populated into list
int i=list.indexOf(someObjectsID); //Where someObjectsID is a String and not a MyClass object

int i will have the indexOf of the MyClass object in list that has ID equal to someObjectsID

3 Answers

If you're open to using a third party library, you can use detectIndex from Eclipse Collections.

int index = ListIterate.detectIndex(list, each -> each.getID().equals(someObjectsID));

If the list is of type MutableList, the detectIndex method is available directly on the list.

MutableList<MyClass> list = Lists.mutable.empty();
int index = list.detectIndex(each -> each.getID().equals(someObjectsID));

Note: I am a committer for Eclipse Collections

There is one absolutely guaranteed, efficient solution to this problem. Nothing else will work nearly so simply or efficiently.

That solution is to just write the loop and not try to get fancy.

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

No need to mess with hashCode or equals. No need to force indexes into streams not designed for them.

Override hashCode & equals in your custom object, then indexOf will Just Work (tm).

Related