- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Search a particular element in a LinkedList in Java
A particular element can be searched in a LinkedList using the method java.util.LinkedList.indexOf(). This method returns the index of the first occurance of the element that is searched. If the element is not available in the LinkedList, then this method returns -1.
A program that demonstrates this is given as follows −
Example
import java.util.LinkedList; public class Demo { public static void main(String[] args) { LinkedList<String> l = new LinkedList<String>(); l.add("A"); l.add("B"); l.add("C"); l.add("D"); l.add("E"); System.out.println("The index of element B in LinkedList is: " + l.indexOf("B")); System.out.println("The index of element Z in LinkedList is: " + l.indexOf("Z")); } }
Output
The index of element B in LinkedList is: 1 The index of element Z in LinkedList is: -1
Now let us understand the above program.
The LinkedList l is created. Then LinkedList.add() is used to add the elements to the LinkedList. LinkedList.indexOf() returns the index of the first occurrence of “B” and “Z” and that is displayed. A code snippet which demonstrates this is as follows −
LinkedList<String> l = new LinkedList<String>(); l.add("A"); l.add("B"); l.add("C"); l.add("D"); l.add("E"); System.out.println("The index of element B in LinkedList is: " + l.indexOf("B")); System.out.println("The index of element Z in LinkedList is: " + l.indexOf("Z"));
- Related Articles
- Add a single element to a LinkedList in Java
- Remove a specific element from a LinkedList in Java
- Retrieve the last element from a LinkedList in Java
- Replace an element of a Java LinkedList
- Delete first and last element from a LinkedList in Java
- How do you find the element of a LinkedList in Java?
- Check if a particular element exists in Java LinkedHashSet
- How to search for element in a List in Java?
- Java Program to Get the middle element of LinkedList in a single iteration
- Java Program to check if a particular element exists in HashSet
- Get the index of a particular element in an ArrayList in Java
- Implement a stack from a LinkedList in Java
- Get the last index of a particular element in an ArrayList in Java
- LinkedList in Java
- Search an element of ArrayList in Java

Advertisements