Java 根据ArrayList中某个对象的某个属性值对其进行索引
如果ArrayList包含Book对象,如何根据其属性“ID”值获取特定对象的索引Java 根据ArrayList中某个对象的某个属性值对其进行索引,java,arraylist,Java,Arraylist,如果ArrayList包含Book对象,如何根据其属性“ID”值获取特定对象的索引 您可以通过使用IntStream生成索引,然后对给定条件使用过滤器操作,然后使用.findFirst()…检索索引,如下所示: int index = IntStream.range(0, list.size()) .filter(i -> list.get(i).id == searchId) .findFirst()
您可以通过使用
IntStream
生成索引,然后对给定条件使用过滤器
操作,然后使用.findFirst()…
检索索引,如下所示:
int index = IntStream.range(0, list.size())
.filter(i -> list.get(i).id == searchId)
.findFirst()
.orElse(-1);
适用于8以下的Java版本解决方案
除其他Java 8工作解决方案外,还有一种解决方案适用于使用早于8的Java版本的用户:
int idThatYouWantToCheck = 12345; // here you can put any ID you're looking for
int indexInTheList = -1; // initialize with negative value, if after the for loop it becomes >=, matching ID was found
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getId == idThatYouWantToCheck) {
indexInTheList = i;
break;
}
}
int-id您想要检查=12345;//在这里你可以放任何你要找的身份证
int indexInTheList=-1;//使用负值初始化,如果在for循环之后它变成>=,则找到匹配的ID
对于(int i=0;i
这正是您想要的:
private static int findIndexById(List<Book> list, int id) {
int index = -1;
for(int i=0; i < list.size();i++){
if(list.get(i).id == id){
return i;
}
}
return index;
}
即使您使用的是Java8,也不建议您使用流;for循环比流快 您希望获取哪个项目的索引?请为我们澄清您的问题。我想根据ID值获取对象的索引使用
循环进行迭代,测试每个项目以找到索引。理想情况下,将它们按ID放入地图,否则下面的流API答案就可以了。请注意,您可以分别保留两个列表名称到ID
和ID到名称
,节省了迭代时间,因为搜索数量将很大(据我猜测)
int idThatYouWantToCheck = 12345; // here you can put any ID you're looking for
int indexInTheList = -1; // initialize with negative value, if after the for loop it becomes >=, matching ID was found
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getId == idThatYouWantToCheck) {
indexInTheList = i;
break;
}
}
private static int findIndexById(List<Book> list, int id) {
int index = -1;
for(int i=0; i < list.size();i++){
if(list.get(i).id == id){
return i;
}
}
return index;
}
int index = findIndexById(list,4);