How to get the index of an element in a list in Java

The best way to find the position/index of an element in a list is the method List.indexOf(Object o). But what exactly does this method do?

What does indexOf do?

The index is the position of the element in the list, starting at 0. So the first element has index 0, the second index 1, and so on.

The indexOf() method returns the position of the first element in the list, which is equal to the passed object. The comparison in the implementation is done with equals. If the object is not found in the list, -1 is returned.


Example : indexOf
List<String> names = Arrays.asList("Alex", "Jean", "Emily", "Bob");

System.out.println(names.indexOf("Alex"));   // 0
System.out.println(names.indexOf("Emily"));  // 2
System.out.println(names.indexOf("Ali"));    //-1
System.out.println(names.indexOf(null));     //-1

This method only finds objects for which a comparison with equals results in true. If you want to find out the position of an element with a certain ID or a name, you would first have to filter the list and then call indexOf with the result.
java-mcq-multiple-choice-questions-and-answersJava MCQ – Multiple Choice Questions and Answers – OOPsThis collection of Java Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Java OOPs”.   1. Which of the…Read More mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *