ArrayList中对象的索引根据其属性值之一

问题描述 投票:3回答:3

我有一个包含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;
    }

}
java arraylist
3个回答
2
投票

您可以使用IntStream生成索引,然后根据给定的条件使用filter操作,然后使用.findFirst()...检索索引,如下所示:

int index = IntStream.range(0, list.size())
                     .filter(i -> list.get(i).id == searchId)
                     .findFirst()
                     .orElse(-1);

1
投票

对于Java版本低于8的解决方案

作为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;
    } 
}

1
投票

这正是您正在寻找的:

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);

即使您使用的是Java 8,也不建议您使用Java。 for循环比流更快。 Reference

© www.soinside.com 2019 - 2024. All rights reserved.