Java LinkedHashSet

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 in the order in which they were inserted. When cycling through LinkedHashSet using an iterator, the elements will be returned in the order in which they were inserted.

There are some key points to remember about LinkedHashSet :

  1. LinkedHashSet class contains unique elements like HashSet.
  2. LinkedHashSet class provides all optional set operations and permits null elements.
  3. LinkedHashSet class is non-synchronized.
  4. LinkedHashSet class maintains insertion order.

Creating a LinkedHashSet

In order to create a linked hash set, we must import the java.util.LinkedHashSet package first.


                        Set set = new LinkedHashSet();
                                (or)
                        LinkedHashSet linkedHashSet = new LinkedHashSet();
                    
Creating an LinkedHashSet of a specific type

                      // create Integer type linkedHashSet
                      LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<Integer>();

                      // create String type linkedHashSet
                      LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>();

                      // LinkedHashSet with 8 capacity and 0.75 load factor
                      LinkedHashSet<Integer> numbers = new LinkedHashSet<Integer>(8, 0.75);
                  

Notice, the part new LinkedHashSet<>(8, 0.75). Here, the first parameter is capacity and the second parameter is loadFactor.

  1. capacity - The capacity of this hash set is 8. Meaning, it can store 8 elements.
  2. loadFactor - The load factor of this hash set is 0.75. This means, whenever our hash table is filled by 75%, the elements are moved to a new hash table of double the size of the original hash table.

HashSet constructos

In order to create a HashSet, we need to create an object of the HashSet class. The HashSet class consists of various constructors that allow the possible creation of the HashSet. The following are the constructors available in this class.

Constructor Description Example
LinkedHashSet() This constructor is used to create a default LinkedHashSet LinkedHashSet hs = new LinkedHashSet();
LinkedHashSet(Collection C) Used in initializing the LinkedHashSet with the elements of the collection C. LinkedHashSet hs = new LinkedHashSet(Collection c);
LinkedHashSet(int size) Used to initialize the size of the LinkedHashSet with the integer mentioned in the parameter. LinkedHashSet hs = new LinkedHashSet(int size);
LinkedHashSet(int capacity, float fillRatio) Can be used to initialize both the capacity and the fill ratio, also called the load capacity of the LinkedHashSet with the arguments mentioned in the parameter. When the number of elements exceeds the capacity of the hash set is multiplied with the fill ratio thus expanding the capacity of the LinkedHashSet. LinkedHashSet hs = new LinkedHashSet(int capacity, int fillRatio);
Methods of LinkedHashSet

The LinkedHashSet class provides methods that allow us to perform various operations on the linked hash set.

Method Name Description
add() inserts the specified element to the linked hash set.
addAll() inserts all the elements of the specified collection to the linked hash set.
remove() removes the specified element from the linked hash set.
removeAll() removes all the elements from the linked hash set.
retainAll() To perform the intersection between two sets, we can use the retainAll() method.
containsAll() To check if a set is a subset of another set or not.
clone() Creates a copy of the LinkedHashSet.
contains() Searches the LinkedHashSet for the specified element and returns a boolean result.
isEmpty() Checks if the LinkedHashSet is empty.
size() Returns the size of the LinkedHashSet.
clear() Removes all the elements from the LinkedHashSet.
Basic Operations on HashSet

The HashSet class provides various methods to perform different operations on hashset. We will look at some commonly used hashset operations.

  1. ▪ Insert Elements to LinkedHashSet
  2. ▪ Access LinkedHashSet Elements
  3. ▪ Remove Elements from LinkedHashSet
Set Operations: The various methods of the HashSet class can also be used to perform various set operations.
  1. ▪ Union of Sets
  2. ▪ Intersection of Sets
  3. ▪ Difference of Sets
  4. ▪ Subset

Insert Elements to LinkedHashSet

add(), addAll() methods is used to insert elements into LinkedHashSet.


                        import java.util.LinkedHashSet;

                        public class LinkedHashSetInsertExample {
                            public static void main(String[] args) {
                                LinkedHashSet<Integer> evenNumber = new LinkedHashSet<Integer>();

                                // Using add() method
                                evenNumber.add(2);
                                evenNumber.add(4);
                                evenNumber.add(6);
                                System.out.println("HashSet: " + evenNumber);

                                LinkedHashSet<Integer> numbers = new LinkedHashSet<Integer>();
                                
                                // Using addAll() method
                                numbers.addAll(evenNumber);
                                numbers.add(5);
                                System.out.println("New LinkedHashSet: " + numbers);
                            }
                        }
                    
Access LinkedHashSet Elements

To access the elements of a LinkedHashSet, we can use the iterator() method. In order to use this method, we must import the java.util.Iterator package.


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

                        public class LinkedHashSetAccessExample {
                            public static void main(String[] args) {
                                LinkedHashSet<Integer> numbers = new LinkedHashSet<Integer>();
                                numbers.add(2);
                                numbers.add(5);
                                numbers.add(6);
                                System.out.println("LinkedHashSet: " + numbers);

                                // Calling iterator() method
                                Iterator<Integer> iterate = numbers.iterator();
                                System.out.print("LinkedHashSet using Iterator: ");
                                // Accessing elements
                                while(iterate.hasNext()) {
                                    System.out.println(iterate.next());
                                }
                            }
                        }

                    
Remove Elements

remove(), removeAll() methods are used to remove specified element or all the elements from the LinkedHashSet collection.


                        import java.util.LinkedHashSet;

                        public class LinkedHashSetRemove {
                            public static void main(String[] args) {
                                LinkedHashSet<Integer> numbers = new LinkedHashSet<>();
                                numbers.add(2);
                                numbers.add(5);
                                numbers.add(6);
                                System.out.println("LinkedHashSet: " + numbers);

                                // Using remove() method
                                boolean value1 = numbers.remove(5);
                                System.out.println("Is 5 removed? " + value1);

                                boolean value2 = numbers.removeAll(numbers);
                                System.out.println("Are all elements removed? " + value2);
                            }
                        }
                    
Union of Sets

To perform the union between two sets, we can use the addAll() method. For example:


                        import java.util.LinkedHashSet;

                        public class UnionOfSetExample {
                            public static void main(String[] args) {
                                LinkedHashSet<Integer> evenNumbers = new LinkedHashSet<>();
                                evenNumbers.add(2);
                                evenNumbers.add(4);
                                System.out.println("LinkedHashSet1: " + evenNumbers);

                                LinkedHashSet<Integer> numbers = new LinkedHashSet<>();
                                numbers.add(1);
                                numbers.add(3);
                                System.out.println("LinkedHashSet2: " + numbers);

                                // Union of two set
                                numbers.addAll(evenNumbers);
                                System.out.println("Union is: " + numbers);
                            }
                        }
                    
Intersection of Sets

To perform the intersection between two sets, we can use the retainAll() method. For example:


                        import java.util.LinkedHashSet;

                        public class IntersectionOfSetsExample {
                            public static void main(String[] args) {
                                LinkedHashSet<Integer> primeNumbers = new LinkedHashSet<>();
                                primeNumbers.add(2);
                                primeNumbers.add(3);
                                System.out.println("LinkedHashSet1: " + primeNumbers);

                                LinkedHashSet<Integer> evenNumbers = new LinkedHashSet<>();
                                evenNumbers.add(2);
                                evenNumbers.add(4);
                                System.out.println("LinkedHashSet2: " + evenNumbers);

                                // Intersection of two sets
                                evenNumbers.retainAll(primeNumbers);
                                System.out.println("Intersection is: " + evenNumbers);
                            }
                        }

                    
Difference of Sets

To calculate the difference between the two sets, we can use the removeAll() method. For example:


                        import java.util.LinkedHashSet;

                        public class DifferenceOfSets {
                            public static void main(String[] args) {
                                LinkedHashSet<Integer> primeNumbers = new LinkedHashSet<>();
                                primeNumbers.add(2);
                                primeNumbers.add(3);
                                primeNumbers.add(5);
                                System.out.println("LinkedHashSet1: " + primeNumbers);

                                LinkedHashSet<Integer> oddNumbers = new LinkedHashSet<>();
                                oddNumbers.add(1);
                                oddNumbers.add(3);
                                oddNumbers.add(5);
                                System.out.println("LinkedHashSet2: " + oddNumbers);

                                // Difference between LinkedHashSet1 and LinkedHashSet2
                                primeNumbers.removeAll(oddNumbers);
                                System.out.println("Difference : " + primeNumbers);
                            }
                        }
                    
Subset

To check if a set is a subset of another set or not, we can use the containsAll() method. For example:


                        import java.util.LinkedHashSet;

                        public class SubsetsExample {
                            public static void main(String[] args) {
                                LinkedHashSet<Integer> numbers = new LinkedHashSet<>();
                                numbers.add(1);
                                numbers.add(2);
                                numbers.add(3);
                                numbers.add(4);
                                System.out.println("LinkedHashSet1: " + numbers);

                                LinkedHashSet<Integer> primeNumbers = new LinkedHashSet<>();
                                primeNumbers.add(2);
                                primeNumbers.add(3);
                                System.out.println("LinkedHashSet2: " + primeNumbers);

                                // Check if primeNumbers is a subset of numbers
                                boolean result = numbers.containsAll(primeNumbers);
                                System.out.println("Is LinkedHashSet2 is subset of LinkedHashSet1? " + result);
                            }
                        }