我有一个包含 Book 对象的 ArrayList,如何根据其属性“ID”值获取特定对象的索引?
public static void main(String[] args) {
ArrayList<Book> list = new ArrayList<>();
list.add(new Book("foods", 1));
list.add(new Book("dogs", 2));
list.add(new Book("cats", 3));
list.add(new Book("drinks", 4));
list.add(new Book("sport", 5));
int index =
}
这本书类:
public class Book {
String name;
int id;
public Book(String name, int Id) {
this.name=name;
this.id=Id;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
最佳答案
您可以通过使用 IntStream
生成索引,然后根据您给定的条件使用 filter
操作,然后使用 .findFirst() 检索索引...
如下图:
int index = IntStream.range(0, list.size())
.filter(i -> list.get(i).id == searchId)
.findFirst()
.orElse(-1);
关于java - 根据其属性值之一在 ArrayList 中的对象索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49083998/