Reputation: 33
I have an ArrayList contains Book objects, how can I get the index of a specific object according to its property "ID" value ?
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 =
}
this Book class :
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;
}
}
Upvotes: 3
Views: 879
Reputation: 961
This is precisely what you are looking for:
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;
}
And call it like this:
int index = findIndexById(list,4);
Even if you are using Java 8, for what you are doing streams are not suggested; for-loop is faster than streams. Reference
Upvotes: 1
Reputation: 3609
As an addition to other, Java 8 working solution, there is a solution for those working with Java versions earlier than 8:
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;
}
}
Upvotes: 2
Reputation: 56433
You can do so by using an IntStream
to generate the indices then use a filter
operation for your given criteria then retrieve the index using .findFirst()...
as shown below:
int index = IntStream.range(0, list.size())
.filter(i -> list.get(i).id == searchId)
.findFirst()
.orElse(-1);
Upvotes: 2