Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java Program to Get Elements By Index from LinkedHashSet
Next article icon

Java Program to Get Elements By Index from LinkedHashSet

Last Updated : 24 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

LinkedHashSet is a pre-defined class in Java that is similar to HashSet. Unlike HashSet In LinkedHashSet insertion order is preserved. In order to get element by Index from LinkedHashSet in Java, we have multiple ways.

Illustration:

Input      : 2, 3, 4, 2, 7;
Processing : index = 4;
Output : Element at index 4 is : 7

Methods:

  1. A naive approach using the iteration count method
  2. Converting LinkedHashSet to Array
  3. Converting LinkedHashSet to List

Method 1: Naive approach using iteration method for index count and to get the element at the given index.

Algorithm

  1. Use iterator to traverse to our LinkedHashSet.
  2. Initiate out index pointer currentindex = 0
  3. Start the iteration using a while loop and if the current index becomes equal to the given index print the element.
Pseudo Code: 
Iterator<Integer> it = LHS.iterator();
while(it.hasNext()) {}

Implementation:

Example 1

Java
// Java Program to Get Elements by Index from LinkedHashSet // Using iteration count method  // Importing generic java libraries import java.io.*; import java.util.*;  // Main class class GFG {      // Main driver method     public static void main(String[] args)      {         // Adding elements to LinkedHashSet         // Custom inputs         LinkedHashSet<Integer> LHS = new LinkedHashSet<>();         LHS.add(2);         LHS.add(3);         LHS.add(4);         LHS.add(2);         LHS.add(7);          // Custom index chosen to get the element         // present at that index         int index = 4;          Iterator<Integer> it = LHS.iterator();          // Assigning initial values         int currIndex = 0;         Integer CurrentElement = null;          // Condition check using hasNext(), whick         // returns true if another token as input         while (it.hasNext()) {              // next element using iterator is             // assigned to variable             CurrentElement = it.next();              // Variable condition check             if (currIndex == index - 1) {                 System.out.println("Element at index "                                    + index + " is : "                                    + CurrentElement);                 break;             }              // If condition fails, so             // Incrementing current index             currIndex++;         }     } } 

Output
Element at index 4 is : 7

Time Complexity: O(n)

Method 2: LinkedHashSet is converted to Array by which element can be accessed at the given index.

Algorithm: 

  1. Convert given LinkedHashSet to Array using toArray() method.
  2. Accessing the element on the given index in the array.
Pseudo Code:
Integer[] LHSArray = new Integer[LHS.size()];
LHSArray = LHS.toArray(LHSArray);

Example  

Java
// Java Program to Get Elements by Index from LinkedHashSet // By converting LinkedHashSet to Array  // Importing generic java libraries import java.io.*; import java.util.*;  // Main class class GFG {      // Main driver method     public static void main(String[] args)     {         // Creating a LinkedHashSet         LinkedHashSet<Integer> LHS = new LinkedHashSet<>();          // Adding elements() to LinkedHashSet         LHS.add(2);         LHS.add(3);         LHS.add(4);         LHS.add(2);         LHS.add(7);          // Custom index chosen from LinkedHashSet         int index = 4;          // Converting LnkedHashMap to Array         Integer[] LHSArray = new Integer[LHS.size()];         LHSArray = LHS.toArray(LHSArray);          // Printing desired value at index in array,         // chosen above index from LinkedHashap         System.out.println("Element at index " + index                            + " is : "                            + LHSArray[index - 1]);     } } 

Output
Element at index 4 is : 7

Time Complexity: O(1)

Method 3: LinkedHashSet to be converted to List to get the desired element at the given index.

Algorithm 

  1. Convert our LinkedHashSet to List like ArrayList.
  2. Using get() method to get an element in a given index.
Pseudo Code : List<Integer> LHSList =new ArrayList<>(LHS);
where LHS is name of our LinkedHashSet

Implementation: 

Java
// Java Program to Get Elements by Index from LinkedHashSet // By converting LinkedHashSet to List  // Importing java generic libraries import java.util.*; import java.io.*;  // Main class class GFG {      // Main driver method     public static void main(String[] args)     {         // Creating a LinkedHashSet         LinkedHashSet<Integer> LHS = new LinkedHashSet<>();          // Adding elements to LinkedHashSet         LHS.add(2);         LHS.add(3);         LHS.add(4);         LHS.add(2);         LHS.add(7);          // Custom index chosen to retrieve value         int index = 4; // User-provided index (1-based)          // Step 1: Convert LinkedHashSet to List         List<Integer> LHSList = new ArrayList<>(LHS);          // Step 2: Adjust index to zero-based and check bounds         int zeroBasedIndex = index - 1; // Convert to zero-based index         if (zeroBasedIndex >= 0 && zeroBasedIndex < LHSList.size()) {             System.out.println("Element at index " + index + " is : " + LHSList.get(zeroBasedIndex));         } else {             System.out.println("Index out of bounds");         }     } } 

Output
Element at index 4 is : 7 

Next Article
Java Program to Get Elements By Index from LinkedHashSet

S

sambhavshrivastava20
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Java Programs
  • Technical Scripter 2020
  • java-LinkedHashSet
Practice Tags :
  • Java

Similar Reads

    How to Get Random Elements from LinkedHashSet in Java?
    LinkedHashSet is used to maintain the insertion order and for generating random elements from LinkedHashSet we will use Random Class to generate a random number between 0 and the LinkedHashSet size. That random number will act as the index of LinkedHashSet. We can get a random element in three ways:
    3 min read
    Java Program to Iterate LinkedHashSet Elements
    The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements
    3 min read
    How to Print LinkedHashSet Elements in Java?
    LinkedHashSet is a child class of HashSet in which duplicates are not allowed but the insertion order is preserved. The elements are printed in the same order in which they were inserted. There are several ways to print LinkedHashSet elements: By simply printing the elementsBy using enhanced for loo
    4 min read
    How to Get the Last Element from LinkedHashSet in Java?
    The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements
    2 min read
    Java Program to Get Elements of a LinkedList
    Linked List is a linear data structure, in which the elements are not stored at the contiguous memory locations. Here, the task is to get the elements of a LinkedList. 1. We can use get(int variable) method to access an element from a specific index of LinkedList: In the given example, we have used
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences