X
    Categories: Java Core

Java LinkedHashSet Example

LinkedHashSet class in Java differs from HashSet as its implementation maintains a doubly-linked list across all elements. This linked list defines the iteration ordering which is the order in which the elements were inserted into the set. It is called an insertion-order. If an element is re-inserted into the set, the insertion order is not affected by it. This implementation is preferred by some as it spares its users from the unspecified and chaotic ordering provided by HashSet.

Advantages of LinkedHashSet

  • LinkedHashSet maintains insertion order of elements
  • The time complexity of insertion, removal and retrieval operations is O(1) (constant time).
  • LinkedHashSet allows 1 null element.
  • LinkedHashSet uses equals() and hashCode() and thus makes it possible to remove possible duplicate elements.

Inheritance diagram

Inheritance diagram of LinkedHashSet



Constructors in LinkedHashSet

  1. LinkedHashSet(): initialises a new linked hash set with default initial capacity of 16 and load factor of 0.75.
  2. LinkedHashSet(Collection<? extends E> c): initialises a new linked hash set with same elements as the specified collection.
  3. LinkedHashSet(int initialCapacity): initialises a new linked hash set with the specified initial capacity.
  4. LinkedHashSet(int initialCapacity, float loadFactor): initialises a new linked hash set with the specified capacity and load factor.

Methods in LinkedHashSet

  1. Methods inherited from class java.util.HashSet: addclearclonecontainsisEmptyiteratorremovesize
  2. Methods inherited from class java.util.AbstractSet: equalshashCoderemoveAll
  3. Methods inherited from class java.util.AbstractCollection: addAllcontainsAllretainAlltoArraytoArraytoString
  4. Methods inherited from class java.lang.Object: finalizegetClassnotifynotifyAllwaitwaitwait
  5. Methods inherited from interface java.util.Set: addaddAllclearcontainscontainsAllequalshashCodeisEmptyiteratorremoveremoveAllretainAllsizetoArraytoArray

For documentation for all the methods, you can visit the Oracle official documentation page.

 

Iterating through LinkedHashSet using Iterator()

import java.util.*;  
class LinkedHashSetExample{  
     public static void main(String args[]){  
        LinkedHashSet<String> animals=new LinkedHashSet();  
               animals.add("Elephant");    
               animals.add("Tiger");    
               animals.add("Lion");   
 
               Iterator<String> iterator=animals.iterator();  
               while(iterator.hasNext())  {  
                     System.out.println(iterator.next());  
               }  
      }  
}

Output:

Elephant
Tiger
Lion

Iterating through LinkedHashSet using For Loop

LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>();
for (int i = 0; i < linkedHashSet.size(); i++) {
    System.out.println(linkedHashSet.get(i));
}

Iterating though LinkedHashSet using Enchanced For Loop

for (String temp : linkedHashSet) {
    System.out.println(temp);
}

Iterating through LinkedHashSet using While Loop

int i = 0;
while (i < linkedHashSet.size()) {
    System.out.println(linkedHashSet.get(i));
    i++;
}

Example program using LinkedHashSet

import java.util.LinkedHashSet;   
public class LinkedHashSetExample  
{   
    public static void main(String[] args)  
    {   
        LinkedHashSet<String> coins =  
                           new LinkedHashSet<String>();   
  
        // Adding element to LinkedHashSet   
        coins.add("5");   
        coins.add("10");   
        coins.add("20");   
        coins.add("50"); 
        coins.add("100"); 
  
        // Adding a duplicate would result in no addition of the element  
        coins.add("5");
        // Adding another coin value
        coins.add("75");   
  
        System.out.println("Size of the list = " + 
                                    coins.size());   
        System.out.println("Original LinkedHashSet:" + coins);   
        System.out.println("Removing 75 from LinkedHashSet: " + 
                            coins.remove("75"));    
        System.out.println("Checking if 50 is present=" +  
                            coins.contains("50")); 
        System.out.println("Updated LinkedHashSet: " + coins);   
    }   
}

Output:

Size of LinkedHashSet=5
Original LinkedHashSet:[5, 10, 20, 50, 75, 100]
Removing 75 from LinkedHashSet: true
Checking if 50 is present=true
Updated LinkedHashSet:[5, 10, 20, 50, 100]

 

 

0 0 votes
Article Rating
ym_coding:
Related Post