How to find the index of an element in the LinkedList in Java?
Use the indexOf method of the LinkedList class to find the index of the first occurrence of an element in the list.
1 | public int indexOf[Object o] |
The indexOf method returns the index of the first occurrence of the specified element object in the list. If the specified element is not found in the list. it returns -1.
Similarly, use the lastIndexOf method of the LinkedList class to find the last occurrence of the specified element in the list.
1 | public int lastIndexOf[Object o] |
This method also returns -1 if the element is not found in the list, otherwise, it returns the index of the last occurrence of the specified element in the list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | import java.util.LinkedList; public class FindElementIndexInLinkedListExample { public static void main[String[] args] { //create new LinkedList object LinkedList linkedListNumbers = new LinkedList[]; //add elements linkedListNumbers.add[1]; linkedListNumbers.add[2]; linkedListNumbers.add[3]; linkedListNumbers.add[1]; linkedListNumbers.add[2]; linkedListNumbers.add[3]; /* * To find first occurrence of an element in LinkedList, use * the indexOf method */ int index = linkedListNumbers.indexOf[3]; if[index == - 1]{ System.out.println["Element not found"]; }else{ System.out.println["Element found at index " + index]; } /* * To find last occurrence of an element, use the * lastIndexOf method */ index = linkedListNumbers.lastIndexOf[3]; if[index == - 1]{ System.out.println["Element not found"]; }else{ System.out.println["Last occurrence of an element found at index " + index]; } //this will return -1 as the linked list does not contain 4 System.out.println[ linkedListNumbers.indexOf[4] ]; } } |
Output
1 2 3 | Element found at index 2 Last occurrence of an element found at index 5 -1 |