Search for items in LinkedList in Java
In this tutorial, we'll look at ways to find an item in a LinkedList using the following two methods:public indexOf(Object o): returns the index of the first occurrence of the specific object, otherwise -1 if the list does not contain this element.
public int lastIndexOf(Object o): returns the index of the last occurrence of the specific object, otherwise -1 if the list does not contain that element.
Example:
Here is a LinkedList that contains String elements. We use indexOf() and lastIndexOf() to look for a String:
import java.util.LinkedList;Output:
public class Search {
public static void main(String[] args) {
// create an instance of LinkedList
LinkedListlinkedlist = new LinkedList ();
// insert elements
linkedlist.add("abc");
linkedlist.add("abcd");
linkedlist.add("bc");
linkedlist.add("def");
linkedlist.add("abcd");
linkedlist.add("ijk");
linkedlist.add("ghi");
//find the first occurrence encountered
int procc = linkedlist.indexOf("abcd");
System.out.println("First occurrence: " + procc);
//find the last occurrence encountered
int drocc = linkedlist.lastIndexOf("abcd");
System.out.println("Last Occurrence: " + drocc);
}
}
First Occurrence: 1
Last Occurrence: 4