CodeGym /Java Blog /Java Collections /LinkedHashSet in Java
Author
Volodymyr Portianko
Java Engineer at Playtika

LinkedHashSet in Java

Published in the Java Collections group
Speaking of the LinkedHashSet class in Java, we need to mention that it implements the Set interface. LinkedHashSet creates a collection that stores elements in a hash table but maintains the insertion order of elements unlike its HashSet counterpart.

What is Set in Java

Let us briefly recall that the Set interface defines a set (set). It extends Collection and defines the behavior of collections that do not allow duplicate elements. Thus, the add() method returns false if an attempt is made to add a duplicate element to the set. The interface does not define any additional methods of its own. The Set interface takes care of the uniqueness of stored objects, uniqueness is determined by the implementation of the equals() method. Therefore, if objects of the created class will be added to the Set, it is desirable to override the equals() method.

LinkedHashSet class

Before talking about the LinkedHashSet class, we need to mention its close relative, the HashSet class. HashSet implements the Set interface. It creates a collection that stores the elements in a hash table. The elements of a hash table are stored as key-value pairs. The key specifies the cell (or segment) to store the value. The content of the key is used to determine a unique value called a hash code. We can think of a hash code as an object identifier, although it doesn't have to be unique. This hash code also serves as an index to which the data associated with the key is stored. The LinkedHashSet Java class extends HashSet without adding any new methods. LinkedHashSet allows you to quickly check for the existence of an entry, just like HashSet, but contains an ordered list inside. This means that it stores the insertion order of the elements. In other words, LinkedHashSet maintains a linked list of set elements in the order they were inserted. This allows ordered iteration of insertion into a set. But this causes the LinkedHashSet class to perform operations longer than the HashSet class.

Important Features of LinkedHashSet

  • We can store unique elements only in a LinkedHashSet

  • LinketHashSet let us to extract elements in the same order that we insert

  • LinkedHashSet is Not Synchronized

  • LinkedHashSet allows storing null elements

  • LinkedHashSet uses a hashing technique to store elements at a specified index based on a hash code

LinkedHashSet Methods

In addition to the methods inherited from its parent classes, HashSet defines the following methods:
  • boolean add(Object o) adds the specified element to this set if it is not already present.

  • void clear() removes all elements from this set.

  • Object clone() returns a shallow copy of this LinkedHashSet instance: the elements themselves are not cloned.

  • boolean contains(Object o) returns true if this set contains the specified element.

  • boolean isEmpty() returns true if this set contains no elements.

  • Iterator iterator() returns an iterator over the elements of this set.

  • boolean remove(Object o) removes the specified element from this set, if present.

  • int size() returns the number of elements in this set (its number of elements).

Easy LinkedHashSet examplesIn the example below we show initialization of the LinkedHashSet object and using add() method to fill the set in.

import java.util.LinkedHashSet;
import java.util.Set;

   public class LinkedHashSetEx1 {
       public static void main(String[] args) {
//LinkedHashSet() Init            
Set<String> set = new LinkedHashSet<>();
//adding elements to LinkedHashSet 
           set.add("Re"); //first added element 
           set.add("Do");
           set.add("Fa");
           set.add("Sol");
           set.add("La");
           set.add("Ti");
           set.add("Mi");//last added element  


           System.out.println(set);
       }
   }
The output is:
[Re, Do, Fa, Sol, La, Ti, Mi]
As you can see, the elements in our set appeared in the same order that we placed them in. LinkedHashSet in Java - 1

Example 2. Adding a duplicate into LinkedHashSet

Let’s put in our LinkedHashSet 7 elements with names of musical scores again and put one new element that is the same as one of elements placed before.

import java.util.LinkedHashSet;
import java.util.Set;

public class LinkedHashSetEx2 {
   public static void main(String[] args) {
           Set<String> set = new LinkedHashSet<>();
           set.add("Re");
           set.add("Do");
           set.add("Fa");
           set.add("Sol");
           set.add("La");
           set.add("Ti");
           set.add("Mi");
           set.add("Sol");
           System.out.println(set);
       }
   }
The output of the program is here:
[Re, Do, Fa, Sol, La, Ti, Mi]
The output of Example two is exactly the same as in the first example. We can’t have two similar elements in the LinkedHashSet collection. When we try to put the second one, it’s just ignored.

Example 3. Removing elements from LinkedHashSet


import java.util.LinkedHashSet;
import java.util.Set;
   public class LinkedHashSet3 {
       public static void main(String[] args) {
           Set<String> set = new LinkedHashSet<>();
           set.add("Re");
           set.add("Do");
           set.add("Fa");
           set.add("Sol");
           set.add("La");
           set.add("Ti");
           set.add("Mi");
           System.out.println(set);
           set.remove("Fa");// removing an element from our set
           set.remove("Score");//trying to remove element that isn't in set
           System.out.println(set.remove("Score"));
           System.out.println("Print our set without elements removed: ");
           System.out.println(set);
           set.clear();
           System.out.println("Print out our set after clear command: ");
           System.out.println(set);
       }
   }
The output of the program is here:
[Re, Do, Fa, Sol, La, Ti, Mi] false Print our set without elements removed: [Re, Do, Sol, La, Ti, Mi] Print out our set after clear command: []
As you can see, the remove() method applied to a non-existent element does not result in a program error. It simply returns false if the element was not removed and true if the element was in the LinkedHashSet and then removed.

LinkedHashSet vs HashSet

These two classes are close relatives. However inside the HashSet it uses HashMap to store objects while LinkedHashSet uses LinkedHashMap. If you don’t need to maintain insertion order but need to store unique objects, it is more appropriate to use HashSet. If you need to maintain the insertion order of elements then LinkedHashSet is your choice. The performance of LinkedHashSet is a bit slower than HashSet because LinkedHashSet uses internal LinkedList to maintain the insertion order of elements. Let’s have an example:

import java.util.*;

public class LinkedHashSetExample1 {

   public static void main(String[] args) {
       // while regular hash set orders its elements according to its hashcode stamps

       Set<Integer> regularHashSet = new HashSet<>();
       regularHashSet.add(7);
       regularHashSet.add(3);
       regularHashSet.add(5);
       regularHashSet.add(65536);
       regularHashSet.add(9);
       // few duplicates
       regularHashSet.add(5);
       regularHashSet.add(7);

       // next will print:
       // > regularHashSet = [65536, 3, 5, 7, 9]
       System.out.println("regularHashSet = " + regularHashSet);

       // linked hash set keeps order of adding unchanged

       Set<Integer> linkedHashSet = new LinkedHashSet<>();
       linkedHashSet.add(7);
       linkedHashSet.add(3);
       linkedHashSet.add(5);
       linkedHashSet.add(65536);
       linkedHashSet.add(9);
       // few duplicates
       linkedHashSet.add(5);
       linkedHashSet.add(7);

       // next will print:
       // > linkedHashSet = [7, 3, 5, 65536, 9]
       System.out.println("linkedHashSet = " + linkedHashSet);
   }
}
The output of the program is:
regularHashSet = [65536, 3, 5, 7, 9] linkedHashSet = [7, 3, 5, 65536, 9]

Using Java LinkedHashSet in real world applications

Since LinkedHashSet allows you to quickly check for the existence of an entry and also stores order, this collection seems to be quite convenient for eliminating duplicates from a list. Or, for example, solving problems like the last recently seen item in my bag. Or, remember such a game, Pokemon Go? LinkedHashSet can store a list of Pokémon you've encountered and the order in which they came across on your path. In this case, the “repeated” Pokémon will no longer be added to the list. Or, for example, a list of bosses by level that you have already met in any game with levels. Or the history of the discovery of cosmic bodies. LinkedHashSet allows you to quickly check whether a space body is already in the list or not, and if it is not there, then add it to the list. Let's take an example of eliminating duplicates.

import java.util.*;

class LinkedHashSetExample2 {
   public static void main(String[] args) {
       List<String> listWithDuplicates = List.of("some","elements","with", "few", "duplicates", "were", "here", "duplicates", "duplicates");

       Set<String> linkedHashSet = new LinkedHashSet<>(listWithDuplicates);
       List<String> listWithoutDuplicates = new ArrayList<>(linkedHashSet);

       // next will print:
       // > listWithDuplicates = [some, elements, with, few, duplicates, here, duplicates, duplicates]
       System.out.println("listWithDuplicates = " + listWithDuplicates);
       // next will print:
       // > listWithoutDuplicates = [some, elements, with, few, duplicates, here]
       System.out.println("listWithoutDuplicates = " + listWithoutDuplicates);

       // -------------------------------------------------------------------------

       // while using regular Hash Set will generally produces some unexpected order
       Set<String> regularHashSet = new HashSet<>(listWithDuplicates);

       // next will print:
       // > linkedHashSet = [some, elements, with, few, duplicates, were, here]
       System.out.println("linkedHashSet = " + linkedHashSet);
       // next will print:
       // > regularHashSet = [here, some, with, duplicates, were, elements, few]
       System.out.println("regularHashSet = " + regularHashSet);
   }
}
The output of the program is here:
listWithDuplicates = [some, elements, with, few, duplicates, were, here, duplicates, duplicates] listWithoutDuplicates = [some, elements, with, few, duplicates, were, here] linkedHashSet = [some, elements, with, few, duplicates, were, here] regularHashSet = [here, some, with, duplicates, were, elements, few]
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION