3

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

}
5
  • You wish to get the index of which item? Please clarify your question for us. Commented Mar 3, 2018 at 12:16
  • i want to get the index of an object according to its ID value Commented Mar 3, 2018 at 12:18
  • Use for loop to iterate, test each item to find the index. Commented Mar 3, 2018 at 12:20
  • Ideally put them into a map by Id, otherwise the stream API answer below will do. Commented Mar 3, 2018 at 12:21
  • just a note, you can keep 2 lists separately name to ids and ids to name, saves time in iterating as number of searches will be large(as far as i guess) Commented Mar 3, 2018 at 12:22

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

Comments

2

For Java Versions Below 8 Solution

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.