Java Program to Get Elements by Index from LinkedHashSet


LinkedHashSet is a class provided by Java which Implements Set Interface. LinkedHashSet is implemented as a hash table with a linked list running through it, so it is more efficient that HashSet and also maintains orders. It is useful when you need a collection that maintains order and does not allow duplicates. In this section, we will discuss different approaches to get the elements from LinkedHashset by index.

What is a LinkedHashSet?

A LinkedHashSet is a collection which is a combination of HashSet collection and a LinkedList collection. A HashSet is an unordered collection and also doesn’t allow duplicates. A LinkedList stores duplicates but also is an ordered collection i.e., it stores the elements in a way in which add elements to the collection. Coming to LinkedHashSet as it is a combination of both hashSet and LinkedList it stores the elements in the same way we add elements to the collection i.e., it is ordered and it also doesn’t allow duplicates to store elements in the collection. Now, let us look at a few basic operations that can be performed on LinkeHashSet.

Basic Operations on LinkedHashSet

Here, we will discuss regarding the basic operations that we can perform on LinkedHashSet using in built methods provided by Java LinkedHashSet Class.

add() − This method helps to add elements to the LinkedHashSet.It accepts a parameter basically the type of elements stored in the LinkedHashSet.

linkedHashSetObject.add(element)

remove() − This method helps to remove elements from the LinkedHashSet. The element passed to this method is removed from the LinkedHashSet.

set.remove("b"); // removes "b" from the set

clear() − This method helps to clear all elements from the LinkedHashSet.

set.clear(); // removes all elements from set

contains() − This method helps to check whether an element which is passed as a parameter is present in the LinkedHashSet. It returns boolean value. If the element is present it returns true else returns false.

boolean val = set.contains('b'); // checks 'b' is present and returns boolean value.

isEmpty() − This method helps to check whether the LinkedHashSet is empty or not. It returns boolean value. If the hashset is empty is it returns true else returns false.

boolean val = set.isEmpty(); // checks hashSet conatians elements or not  

Syntaxes Used

Creating an instance of LinkedHashSet

LinkedHashSet<datatype> set = new LinkedHashSet<>();

iterator() − It iterates over the Linkedhashset and returns the values.

Iterator<datatype> iteratorobjectname = setobject.iterator()

hasNext() − This method is used check whether next element is present in the collection. It is provided by the Iterator Interface in java. It is called on iterator Object.

iteraratorObject.hasNext()

next() − This method helps us to return the next element present in the collection. It is provided by the Iterator Interface in java. It is called on iterator Object.

iteraratorObject.next()

toArray( − This method is used to convert a collection into an array. It returns an array of elements.

collectionobject.toArray()

Now, we will be discussing in detail through java codes how to get the elements by index from a LinkedHashSet.

Approach 1: Using iterator() method

  • Create a LinkedHashSet instance and add elements to the set using the add() method.

  • Declare an index variable and initialize with zero.

  • Create an iterator instance and using hasNext() method check if we have elements in set to be read.

  • Then use while loop to iterate the LinkedHashSet and using Next() method access the elements.

  • Match the condition for index is equal to 2 using if condition and print the element.

Example

In this example, we create a LinkedHashset object and we add a few elements of the set using add() method. We then create an iterator object and initialise a ‘inde’ variable and using wile loop we iterate over the set and increase the index value, if the index value reaches to 2 then we print the element.

import java.util.LinkedHashSet;
import java.util.Iterator;

public class Main {
   public static void main(String[] args) {
      LinkedHashSet<String> set = new LinkedHashSet<>();
      set.add("Hibiscus");
      set.add("Lily");
      set.add("Papaya");
      set.add("Orange");
      set.add("Kiwi");
      Iterator<String> it = set.iterator();
      int index = 0;
      while (it.hasNext()) {
         String x = it.next();
         if (index == 2) {
            System.out.println("Element: "+x);
            break;
         }
         index++;
      }
   }
}

Output

Element : Papaya

Approach 2: Using toArray() method

  • Create a LinkedHashSet instance and add elements to the set using the add() method.

  • Convert the set into an object using the toArray() method.

  • Retrieve the element based on the index from the array and print it.

Example

In this example, we create a LinkedHashSet object and then add a few elements to the set. We then convert set to array using ‘toArray()’ method and then we print values by accessing the array using index.

import java.util.LinkedHashSet;

public class Main {
   public static void main(String[] args) {
      LinkedHashSet<String> set = new LinkedHashSet<>();
      set.add("Hibiscus");
      set.add("Lily");
      set.add("Papaya");
      set.add("Orange");
      set.add("Kiwi");
      Object[] elements = set.toArray();
      int index=2;
      System.out.println("Element is: " + elements[index]);
      System.out.println("Element is: " + elements[4]);
   }
}

Output

Element is: Papaya
Element is: Kiwi

Thus, in this article we have discussed about different approaches of getting elements by Indices from a LinkedHashSet using Java Programming Language.

Updated on: 16-Aug-2023

712 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements