Find indexOf of an object in custom list using one attribute

Sapta lyksmusic :

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

Louis Wasserman :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=124072&siteId=1