How to Search Elements in LinkedList in Java


This example focuses on how to search element of LinkedList using indexOf and lastIndexOf methods in Java.

Source Code

package com.beginner.examples;

import java.util.LinkedList;

public class SearchElementLinkedList {

	public static void main(String[] args) {
		
		//create LinkedList.
		LinkedList linkedList = new LinkedList();
		linkedList.add("A");
		linkedList.add("B");
		linkedList.add("C");
		linkedList.add("D");
		
		/*
		 * To search first occurrence of an element of LinkedList, use
                 * int indexOf(Object element) method.
		 */
		int index = linkedList.indexOf("D");
		if(index != -1)
		{
			System.out.println("D in LinkedList index is : "+ index);
		}
		else
		{
			System.out.println("LinkedList does not contain D");
		}

	}

}

Output:

D in LinkedList index is : 3

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments