Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Java - LinkedHashSet

java_Set

We have seen that in 'HashSet' the insertion order was not maintained. i.e. Say we have inserted the elements A, B and C one after the other in a HashSet. But while displaying the contents of the HashSet, the output might be 'B C A' or 'C B A' and not 'A B C'.



LinkedHashSet

Now, to maintain this order 'LinkedHashSet' comes to rescue. In 'LinkedHashSet', insertion order of the 'Set' is maintained.


Constructors in LinkedHashSet

LinkedHashSet() :  Creates a LinkedHashSet with initial capacity 16 and
                load factor 0.75.


LinkedHashSet(int initialCapacity) :  Creates a HashSet with a custom initial capacity.


HashSet(int initialCapacity, float LoadFactor) :  Creates a HashSet with a custom initial
                             capacity and custom Load Factor.



public class TestCollection{
  public static void main(String[] arg){

  String s1 = new String("Sham");
  String s2 = new String("Paul");
  String s3 = new String("John");

  // We will be adding these Strings to the LinkedHashSet.
  Set linkedHashSet = new LinkedHashSet(); // Declare an LinkedHashSet.
  linkedHashSet.add(s1); // Add the String to the LinkedHashSet.
  linkedHashSet.add(s2);
  linkedHashSet.add(s3);

  System.out.println(linkedHashSet); // Output would be : [Sham,Paul,John]. Order is maintained.

  linkedHashSet.remove(s2); // Deletes "Paul" from the HashSet.
  System.out.println(linkedHashSet); // New output would be : [John,Sham]

  }

1)  We have created three Strings s1, s2 & s3.


2)  Then we have created a LinkedHashSet() using the below format.


Set linkedHashSet = new LinkedHashSet();

3) Next we have added Strings s1,s2 & s3 using the add() method.


linkedHashSet.add(s1);
linkedHashSet.add(s2);
linkedHashSet.add(s3);

4)  When we have printed the values of the LinkedHashSet, we have seen the names are exactly printed in the order they were inserted.

i.e. We have inserted Sham, Paul and then John.

And when we printed the names. Sham, Paul and then John was printed.

This is because the names are inserted serially at the HashSet().


System.out.println(linkedHashSet); // Output would be : [Sham,Paul,John].

5)  linkedHashSet.remove(s2);

Since, 'Paul' is stored in s2. We have removed 'Paul' by using the remove() method.