Java LinkedHashSet tutorial with examples will help you understand how to use the LinkedHashSet class in an easy way. LinkedHashSet in Java is a Hash table and linked list implementation of the Set interface.
Unlike the HashSet class in Java, the LinkedHashSet class offers a predictable iteration order of the elements because it maintains a doubly-linked list running through all of its elements.
The LinkedHashSet class provides constant-time performance for the basic operations like add, remove, and contains and allows null values to be added. However, since it a Set, only one null element can be added to it.
The LinkedHashSet implementation is not synchronized. It means that if the application is multithreaded, we need to synchronize the access. We can get the synchronized set from the LinkedHashSet object using the synchronizedSet
method of the Collections class.
1 |
Set set = Collections.synchronizedSet(new LinkedHashSet()); |
We can also pass an existing object of the linked hash set instead of creating a new one.
How to create new objects of LinkedHashSet class?
The LinkedHashSet class in Java provides several constructors using which we can create new objects.
The default LinkedHashSet constructor creates a new and empty linked hash set object.
1 |
public LinkedHashSet() |
The new LinkedHashSet object created by the default constructor has an initial capacity of 16 and a load factor of 0.75.
1 |
Set<Integer> set = new LinkedHashSet<Integer>(); |
We can also specify the initial capacity and load factor while creating a new LinkedHashSet object using below given overloaded constructors.
1 |
public LinkedHashSet(int initialCapacity) |
1 |
public LinkedHashSet(int initialCapacity, float loadFactor) |
if you want to create a new LinkedHashSet object from another set or a collection, you can use below given overloaded constructor.
1 |
public LinkedHashSet(Collection<? extends E> collection) |
This constructor creates a new LinkedHashSet object having all elements of the specified collection object. The below given example shows how to create a LinkedHashSet object from the existing HashSet object.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Set<Integer> hashSetNumbers = new HashSet<Integer>(); hashSetNumbers.add(1); hashSetNumbers.add(2); hashSetNumbers.add(3); /* * To create a LinkedHashSet object from any other * collection object, use below given constructor. */ Set<Integer> linkedHashSet = new LinkedHashSet<Integer>( hashSetNumbers ); System.out.println("LinkedHashSet contains: " + linkedHashSet); |
Output
1 |
LinkedHashSet contains: [1, 2, 3] |
LinkedHashSet Methods
Below given are some of the important LinkedHashSet methods along with the explanations on how to use them in your code.
How to add elements to the LinkedHashSet objects using the add and addAll methods?
The add
method of the LinkedHashSet class adds the specified element to the linked hash set object.
1 |
public boolean add(E e) |
The add
method returns true if the specified element was not already existed and it is added in the set. If the specified element already existed, it returns false.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Set<Integer> linkedHashSet = new LinkedHashSet<Integer>(); /* * To add elements to the LinkedHashSet object, use * the add method. */ //this will add 1 to the set and return true System.out.println( linkedHashSet.add(1) ); //this return false as element 1 already exists in the set System.out.println( linkedHashSet.add(1) ); System.out.println("LinkedHashSet contains: " + linkedHashSet); |
Output
1 2 3 |
true false LinkedHashSet contains: [1] |
The addAll
method of the LinkedHashSet class adds all elements of the specified collection object to this set.
1 |
public boolean addAll(Collection<? extends E> collection) |
It returns true if this set was changed as a result of this method call, false otherwise. The below given example shows how to add all elements of the HashSet object to LinkedHashSet object using the addAll
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Set<Integer> hashSetNumbers = new HashSet<Integer>(); hashSetNumbers.add(1); hashSetNumbers.add(2); hashSetNumbers.add(3); //create new LinkedHashSet object Set<Integer> linkedHashSet = new LinkedHashSet<Integer>(); //use addAll method to add all elements of HashSet to this set linkedHashSet.addAll(hashSetNumbers); System.out.println("LinkedHashSet contains: " + linkedHashSet); |
Output
1 |
LinkedHashSet contains: [1, 2, 3] |
Note: Since the linked hash set is an implementation of the Set interface, duplicate elements from the specified collection will not be added by the addAll
method.
How to get the size of the LinkedHashSet using the size method?
The LinkedHashSet size
method returns the number of elements stored in the set object.
1 |
public int size() |
It returns 0 if the LinkedHashSet is empty.
1 2 3 4 5 6 7 8 9 10 11 |
Set<Integer> linkedHashSet = new LinkedHashSet<Integer>(); //this will return 0 as the set is empty System.out.println("LinkedHashSet size: " + linkedHashSet.size()); //add a couple of elements linkedHashSet.add(1); linkedHashSet.add(2); //this will return 2 as there are two elements in the set object System.out.println("LinkedHashSet size: " + linkedHashSet.size()); |
Output
1 2 |
LinkedHashSet size: 0 LinkedHashSet size: 2 |
How to check if the LinkedHashSet is empty using the isEmpty method?
The LinkedHashSet isEmpty
method returns true if there are no elements in the set object.
1 |
public boolean isEmpty() |
It returns false if there is at least one element in the set object.
1 2 3 4 5 6 7 8 9 10 |
Set<Integer> linkedHashSet = new LinkedHashSet<Integer>(); //this will return true as the set is empty System.out.println("Is empty? " + linkedHashSet.isEmpty()); //add an elements linkedHashSet.add(1); //this will return false as there is one element System.out.println("Is empty? " + linkedHashSet.isEmpty()); |
Output
1 2 |
Is empty? true Is empty? false |
How to remove elements from the LinkedHashSet using the remove method?
The LinkedHashSet remove
method removes the specified element from the set object.
1 |
public boolean remove(Object o) |
It returns true if the element is found and removed from the set, false otherwise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Set<Integer> linkedHashSet = new LinkedHashSet<Integer>(); linkedHashSet.add(1); linkedHashSet.add(2); linkedHashSet.add(3); /* * Use the remove method to remove elements * from the LinkedHashSet object */ //this will remove 2 from the set and return true System.out.println( linkedHashSet.remove(2) ); //this will return false as the element 4 does not exist in the set System.out.println( linkedHashSet.remove(4) ); System.out.println("LinkedHashSet contains: " + linkedHashSet); |
Output
1 2 3 |
true false LinkedHashSet contains: [1, 3] |
Important Note:
If the LinkedHashSet elements are objects of a custom class (user-defined class), then the class must override the equals
and hashCode
methods for the remove
method to work properly. If the custom class does not override these methods, the remove
method will not be able to find the specified element in the set.
How to clear or remove all elements from the LinkedHashSet using the clear method?
The LinkedHashSet clear
method removes all elements from the set object.
1 |
public void clear() |
The LinkedHashSet object will be empty after this method call.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
Set<Integer> linkedHashSet = new LinkedHashSet<Integer>(); linkedHashSet.add(1); linkedHashSet.add(2); linkedHashSet.add(3); //this will return false as there are 3 elements System.out.println("Is empty? " + linkedHashSet.isEmpty()); /* * To clear or remove all elements from the * LinkedHashSet object, use the clear method. */ linkedHashSet.clear(); //this will return true System.out.println("Is empty? " + linkedHashSet.isEmpty()); System.out.println("LinkedHashSet contains: " + linkedHashSet); |
Output
1 2 3 |
Is empty? false Is empty? true LinkedHashSet contains: [] |
How to remove all LinkedHashSet elements that are also contained in another collection using the removeAll method?
The removeAll
method removes all elements from this set that are also contained in the specified collection object.
1 |
public boolean removeAll(Collection<?> collection) |
In other words, all the common elements between this set object and specified collection object are removed from this set.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
Set<Integer> hashSet = new HashSet<Integer>(); hashSet.add(1); hashSet.add(2); hashSet.add(3); Set<Integer> linkedHashSet = new LinkedHashSet<Integer>(); linkedHashSet.add(2); linkedHashSet.add(3); linkedHashSet.add(4); linkedHashSet.add(5); /* * To remove all common elements between a collection and * this set object, use the removeAll method. */ /* * this will remove all the common elements (i.e. 2 and 3) * from the LinkedHashSet object * */ linkedHashSet.removeAll(hashSet); System.out.println("LinkedHashSet contains: " + linkedHashSet); |
Output
1 |
LinkedHashSet contains: [4, 5] |
How to iterate over the elements of the LinkedHashSet object?
There are several ways using which we can iterate through LinkedHashSet elements.
Using enhanced for loop
1 2 3 4 5 6 7 8 9 10 |
Set<Integer> linkedHashSet = new LinkedHashSet<Integer>(); linkedHashSet.add(1); linkedHashSet.add(2); linkedHashSet.add(3); //iterating using enhanced for loop for(Integer number : linkedHashSet){ System.out.println( number ); } |
Output
1 2 3 |
1 2 3 |
Using an Iterator
We can get an iterator over the elements of the LinkedHashSet using the iterator
method.
1 |
public Iterator<E> iterator() |
Once we get an Iterator object, we can iterate through the LinkedHashSet elements using the hasNext
and the next
methods as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Set<Integer> linkedHashSet = new LinkedHashSet<Integer>(); linkedHashSet.add(1); linkedHashSet.add(2); linkedHashSet.add(3); //get an iterator Iterator<Integer> iterator = linkedHashSet.iterator(); //iterating using the Iterator and while loop while( iterator.hasNext() ){ System.out.println( iterator.next() ); } |
Output
1 2 3 |
1 2 3 |
Using the forEach (Java version 8 and later)
If you are using Java version 8 or later, you can use the forEach
method to iterate the LinkedHashSet as well.
1 2 3 4 5 6 7 8 9 10 |
Set<Integer> linkedHashSet = new LinkedHashSet<Integer>(); linkedHashSet.add(1); linkedHashSet.add(2); linkedHashSet.add(3); //iterating using forEach method linkedHashSet.forEach( element -> { System.out.println( element ); } ); |
Output
1 2 3 |
1 2 3 |
How to check if the element exists in the LinkedHashSet using the contains method?
The LinkedHashSet contains
method returns true if the specified element exists in the set object.
1 |
public boolean contains(Object o) |
It returns false if the LinkedHashSet does not contain the specified element.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Set<Integer> linkedHashSet = new LinkedHashSet<Integer>(); linkedHashSet.add(1); linkedHashSet.add(2); linkedHashSet.add(3); /* * Use the contains method to check if the * specified element exists in the LinkedHashSet object. */ //this will return true as element 2 exists System.out.println( linkedHashSet.contains(2) ); //this will return false as element 4 does not exist System.out.println( linkedHashSet.contains(4) ); |
Output
1 2 |
true false |
Important Note:
Just like the remove
method, if the LinkedHashSet elements are objects of a custom class (user-defined class), then the class must override the equals
and hashCode
methods for the contains
method to work properly. If the custom class does not override these methods, the contains
method will always return false even if the specified element is present in the set.
How to convert LinkedHashSet to an array using the toArray method?
The LinkedHashSet toArray
method returns an array containing all elements of this set object.
1 |
<T> T[] toArray(T[] a) |
The array elements are in the same order that is returned from the linked hash set iterator i.e. insertion order.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Set<Integer> linkedHashSet = new LinkedHashSet<Integer>(); linkedHashSet.add(1); linkedHashSet.add(2); linkedHashSet.add(3); //create new empty array of the same size Integer[] intArray = new Integer[ linkedHashSet.size() ]; /* * To convert LinkedHashSet to array, use the * toArray method and pass the array. */ intArray = linkedHashSet.toArray( intArray ); System.out.println("Array contains: " + Arrays.toString(intArray)); |
Output
1 |
Array contains: [1, 2, 3] |
Important Note:
The toArray
method returns the same array filled with the LinkedHashSet elements if the specified array is large enough. If the array is bigger in size than the LinkedHashSet object, the array element immediately after the LinkedHashSet elements is set to null.
If the specified array is smaller than the linked hash set object, a new array is created, filled with the set elements and returned. The array creation is a costly operation in terms of performance, and to avoid this, it is suggested to pass the array of the same length to the toArray
method.
How to check if the LinkedHashSet contains all elements of other collection using the containsAll method?
The containsAll
method returns true if all the elements of the specified collection are also contained in this set object.
1 |
boolean containsAll(Collection<?> collection) |
It returns true if this linked hash set object contains all the elements of the specified collection object, false otherwise.
The below given example shows how to check if all ArrayList elements are contained in the LinkedHashSet object using the containsAll
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); aListNumbers.add(1); aListNumbers.add(2); aListNumbers.add(3); Set<Integer> linkedHashSet = new LinkedHashSet<Integer>(); linkedHashSet.add(3); linkedHashSet.add(2); linkedHashSet.add(1); /* * To check if all elements of a collection object are * also contained in the LinkedHashSet object, use * the containsAll method */ /* * this will return true as all elements of the * ArrayList are also present in the set object. */ System.out.println( linkedHashSet.containsAll(aListNumbers) ); //remove an element from the LinkedHashSet linkedHashSet.remove(2); /* * this will now return false as the ArrayList element 2 is * missing from the LinkedHashSet object. */ System.out.println( linkedHashSet.containsAll(aListNumbers) ); |
Output
1 2 |
true false |
How to remove all LinkedHashSet elements that are not present in another collection using the retainAll method?
The retainAll
method removes all the elements from this set that are not present in the specified collection.
1 |
boolean retainAll(Collection<?> collection) |
In other words, it retains only elements that are contained in the specified collection object, the rest of the elements of the LinkedHashSet objects are removed from it.
The below given example shows how to keep only common elements between HashSet and LinkedHashSet using the retainAll
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
Set<Integer> hashSet = new HashSet<Integer>(); hashSet.add(1); hashSet.add(2); hashSet.add(3); Set<Integer> linkedHashSet = new LinkedHashSet<Integer>(); linkedHashSet.add(2); linkedHashSet.add(3); linkedHashSet.add(4); linkedHashSet.add(5); /* * To keep only common elements between a collection and * this set object, use the retainAll method. */ /* * this will remove all elements from the LinkedHashSet object * except for 2 and 3 (the common elements between HashSet and * LinkedHashSet) */ linkedHashSet.retainAll(hashSet); System.out.println("LinkedHashSet contains: " + linkedHashSet); |
Output
1 |
LinkedHashSet contains: [2, 3] |
How to clone the LinkedHashSet object using the clone method?
The clone
method of the LinkedHashSet class creates a shallow copy of this set object.
1 |
public Object clone() |
This method does not create a deep copy of the set object, it means that the LinkedHashSet elements are not cloned, only their references are copied.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<Integer>(); linkedHashSet.add(1); linkedHashSet.add(2); linkedHashSet.add(3); /* * To clone the LinkedHashSet object, use * the clone method */ Set<Integer> linkedHashSetCloned = (Set<Integer>) linkedHashSet.clone(); System.out.println("Original LinkedHashSet contains: " + linkedHashSet); System.out.println("Cloned LinkedHashSet contains: " + linkedHashSetCloned); |
Output
1 2 |
Original LinkedHashSet contains: [1, 2, 3] Cloned LinkedHashSet contains: [1, 2, 3] |
How to sort LinkedHashSet elements?
There are a couple of ways using which we can sort LinkedHashSet elements as given below.
1. Sort LinkedHashSet using the TreeSet class
The TreeSet in Java automatically sorts the elements according to their natural order or by the Comparator provided in the TreeSet constructor. We can convert the LinkedHashSet to TreeSet to sort the elements as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<Integer>(); linkedHashSet.add(22); linkedHashSet.add(21); linkedHashSet.add(27); linkedHashSet.add(24); linkedHashSet.add(26); /* * To sort the LinkedHashSet elements, convert it * to the TreeSet using the constructor */ TreeSet<Integer> treeSet = new TreeSet<Integer>( linkedHashSet ); System.out.println("Sorted elements: " + treeSet); |
Output
1 |
Sorted elements: [21, 22, 24, 26, 27] |
Important Note:
If the LinkedHashSet elements are objects of a custom class, then the custom class must either implement the Comparable interface or a custom comparator object must be provided in the TreeSet constructor. If none of these is done, the code will throw java.lang.ClassCastException: class cannot be cast to java.lang.Comparable exception.
2. Using the sort method of the Collections class
To sort the LinkedHashSet using the sort
method of the Collections class, we first need to convert the LinkedHashSet object to a List like ArrayList or LinkedList using the constructor. Once we get the List object, we can sort the LinkedHashSet elements as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<Integer>(); linkedHashSet.add(22); linkedHashSet.add(21); linkedHashSet.add(27); linkedHashSet.add(24); linkedHashSet.add(26); /* * First convert LinkedHashSet to a List object * like ArrayList using the constructor */ ArrayList<Integer> aListNumbers = new ArrayList<Integer>( linkedHashSet ); /* * Now use the sort method of the Collections class */ Collections.sort(aListNumbers); System.out.println("Sorted elements: " + aListNumbers); |
Output
1 |
Sorted elements: [21, 22, 24, 26, 27] |
Important Note:
If the LinkedHashSet elements are objects of a custom class, then the custom class must implement the Comparable interface or a custom comparator must be provided in the overloaded sort
method.
Below given are the additional LinkedHashSet examples which cover the topics in more detail.
Java LinkedHashSet Examples
- How to create new objects of LinkedHashSet class (LinkedHashSet constructors)
- How to add elements to LinkedHashSet object
- How to get the size of the LinkedHashSet in Java
- How to iterate LinkedHashSet elements
- How to remove an element from LinkedHashSet in Java
- How to clear or remove all elements from LinkedHashSet
- How to get the first or last element from LinkedHashSet
- How to print LinkedHashSet elements (display LinkedHashSet elements)
- How to check if LinkedHashSet is empty in Java
- How to check if element exists in LinkedHashSet
- How to get random elements from LinkedHashSet
- How to sort LinkedHashSet in Java
- How to get LinkedHashSet elements by index in Java
- How to find element index in LinkedHashSet
- How to find the minimum or maximum element in LinkedHashSet
- How to copy merge or clone LinkedHashSet in Java
- How to convert LinkedHashSet to array in Java
- How to convert an array to LinkedHashSet in Java
- How to convert ArrayList to LinkedHashSet in Java
- How to convert LinkedHashSet to ArrayList in Java
References:
Java 8 LinkedHashSet Documentation
Please let me know if you liked the Java LinkedHashSet tutorial with examples in the comments section below.