使用一个属性在自定义列表中查找对象的 indexOf

Find indexOf of an object in custom list using one attribute

所以,我有一个自定义 class 和一个 class 类型的数组列表。现在,我想在构成该 class.

的对象的其他属性中仅使用一个对我可用的 ID 来检索此 arraylist 中的对象的索引

在网上看到了几个例子,但我有点困惑,他们重写了hashCode()和equals(),而在equals()中他们检查了所有的属性,我只想检查一下ID 值,因为对于每个对象 ID 都是唯一的。

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

    // Constructors and getters and setters
}

所以,我想要的是,比如这段代码:

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 我将拥有列表中 MyClass 对象的 indexOf,其 ID 等于 someObjectsID

覆盖自定义对象中的 hashCode 和 equals,然后 indexOf 将正常工作 (tm)。

这个问题有一个绝对可靠、有效的解决方案。没有什么比这更简单或有效的了。

该解决方案是只编写循环而不是试图变得花哨。

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

无需混淆 hashCode 或 equals。无需将索引强制到不是为它们设计的流中。

如果您愿意使用第三方库,可以使用 detectIndex from Eclipse Collections

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

如果列表是 MutableList 类型,detectIndex 方法可直接在列表上使用。

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

注意:我是 Eclipse Collections 的提交者