簡體   English   中英

ArrayList中對象的索引根據其屬性值之一

[英]Index of an object in the ArrayList according to one of its properties value

我有一個包含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版本低於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;
    } 
}

這正是您正在尋找的:

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循環比流更快。 參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM