LinkedList

Search elements in LinkedList example

This is an example of how to search the elements in a LinkedList. Searching the elements in a LinkedList implies that you should:

  • Create a new LinkedList.
  • Populate the list with elements, with the add(E e) API method of the LinkedList.
  • Invoke the contains(Object o) API method of LinkedList, to check if the list contains the specified object. It returns true if the list contains the object and false otherwise.
  • Then invoke the indexOf(Object o) API method of LinkedList, to get the index of the first occurance of the specified element in LinkedList or -1 if the specific element is not found.
  • To get the index of the last occurance of the specified element in LinkedList use the lastIndexOf(Object o) operation.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.util.LinkedList;
 
public class SearchLinkedList {
 
  public static void main(String[] args) {
 
    // Create a LinkedList and populate it with elements
    LinkedList linkedList = new LinkedList();
    linkedList.add("element_1");
    linkedList.add("element_2");
    linkedList.add("element_3");
    linkedList.add("element_1");
 
    /*

boolean contains(Object element) operation returns true 

if the LinkedList contains the specified object, false otherwise.
    */
    boolean found = linkedList.contains("element_2");
    System.out.println("Found element_2 : " + found);
 
    /*

int indexOf(Object element) operation returns the index of the 

first occurance of the specified element in LinkedList or -1 if 

the specific element is not found. To get the index of the last 

occurance of the specified element in LinkedList use the

int lastIndexOf(Object element) operation instead.
    */
    int index = linkedList.indexOf("element_3");
    System.out.println("Found element_3 : " + (index == -1?false:true) + ", in position : " + index);
 
    int lastIndex = linkedList.lastIndexOf("element_1");
    System.out.println("Found element_1 : " + (lastIndex == -1?false:true) + ", in position : " + lastIndex);
  }
}

Output:

Found element_2 : true
Found element_3 : true, in position : 2
Found element_1 : true, in position : 3

 
This was an example of how to search the elements in a LinkedList in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button