beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java – Search elements in LinkedList example

By Chaitanya Singh | Filed Under: Java Collections

In this tutorial we will learn how to search elements in LinkedList. We will be using following two methods for searching elements.

public int indexOf(Object o): Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

public int lastIndexOf(Object o): Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.

Example

Here we are having a LinkedList of String elements and we are searching a string using indexOf() and lastIndexOf() methods of LinkedList class.

import java.util.LinkedList;
public class SearchInLinkedList {
 
  public static void main(String[] args) {
 
     // Step1: Create a LinkedList
     LinkedList<String> linkedlist = new LinkedList<String>();
 
     // Step2: Add elements to LinkedList
     linkedlist.add("Tim");
     linkedlist.add("Rock");
     linkedlist.add("Hulk");
     linkedlist.add("Rock");
     linkedlist.add("James");
     linkedlist.add("Rock");
 
     //Searching first occurrence of element
     int firstIndex = linkedlist.indexOf("Rock");
     System.out.println("First Occurrence: " + firstIndex);
 
     //Searching last occurrence of element
     int lastIndex = linkedlist.lastIndexOf("Rock");
     System.out.println("Last Occurrence: " + lastIndex);
  }
}

Output:

First Occurrence: 1
Last Occurrence: 5

Reference:
LinkedList JavaDoc

Enjoyed this post? Try these related posts

  1. Hashtable in java with example
  2. Remove Key-value mapping from TreeMap example
  3. ListIterator in Java with examples
  4. How to clone an ArrayList to another ArrayList
  5. Deque Interface in Java Collections
  6. Java – Remove specific elements from LinkedList example

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

  • Java Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap