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 – Get the index of last occurrence of an element in LinkedList

By Chaitanya Singh | Filed Under: Java.util package

Description

Program to find out the index of last occurrence of an element in LinkedList.

Program

import java.util.LinkedList;
class LinkedListExample {

  public static void main(String[] args) {

     // create a LinkedList
     LinkedList<String> list = new LinkedList<String>();

     // Add elements
     list.add("AA");
     list.add("BB");
     list.add("CC");
     list.add("AA");
     list.add("DD");
     list.add("AA");
     list.add("EE");
 
     // Display LinkedList elements
     System.out.println("LinkedList elements: "+list);

     // get the index of last occurrence of element "AA"
     /* 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. 
      */
     System.out.println("LastIndex of AA:"+list.lastIndexOf("AA"));

     // get the index of last occurrence of element "ZZ"
     /* Note: The element ZZ does not exist in the list so
      * the method lastIndexOf would return -1 for it.
      */
     System.out.println("LastIndex of ZZ:"+list.lastIndexOf("ZZ"));
  }
}

Output:

LinkedList elements: [AA, BB, CC, AA, DD, AA, EE]
LastIndex of AA:5
LastIndex of ZZ:-1

Enjoyed this post? Try these related posts

  1. Convert HashSet to a List/ArrayList
  2. Converting a HashSet to an Array
  3. Java – LinkedList peek(), peekFirst() and peekLast() methods
  4. Clone a HashMap in Java
  5. How to convert a HashSet to a TreeSet
  6. Clone a generic LinkedList in Java

Leave a Reply Cancel reply

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

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap