LinkedHashSet overview

LinkedHashSet is an implementation of Set interface in java

Important features of LinkedHashSet


It contains only unique elements, does not allow duplicates

LinkedHashSet stores elements by using “hashing” mechanism

It maintains the insertion order, elements will be stored in the same order as we insert

It allows null value, since it allows unique values, only one null value is allowed

It is non-synchronized Set by default, however we can synchronize it using Collections utility

We can create LinkedHashSet using constructor as below

  1. LinkedHashSet lhs = new LinkedHashSet();
LinkedHashSet lhs = new LinkedHashSet();

Example :

  1. import java.util.*;
  2. public class LinkedHashSetExample {
  3. public static void main(String args[]) {
  4.  
  5. LinkedHashSet<String> lhs = new LinkedHashSet<String>();
  6.  
  7. lhs.add("java");
  8. lhs.add("c");
  9. lhs.add("c++");
  10. //Adding duplicate elements
  11. lhs.add("java");
  12. lhs.add("c++");
  13. //Adding null values
  14. lhs.add(null);
  15. lhs.add(null);
  16.  
  17. //Displaying HashSet elements
  18. System.out.println(lhs);
  19. }
  20. }
import java.util.*;
public class LinkedHashSetExample {
public static void main(String args[]) {

LinkedHashSet<String> lhs = new LinkedHashSet<String>();

lhs.add("java");
lhs.add("c");
lhs.add("c++");
//Adding duplicate elements
lhs.add("java");
lhs.add("c++");
//Adding null values
lhs.add(null);
lhs.add(null);

//Displaying HashSet elements
System.out.println(lhs);
}
}


Note : We can observe in output, that duplicate elements are not present including Null duplicate value and 
            also insertion order is maintained

When to use LinkedHashSet ?

LinkedHashSet should be used whenever we want to store only unique elements in a collection and we are interested to maintain the order of insertion

When not use LinkedHashSet ?

LinkedHashSet should not be used whenever we need to allow duplicate elements and insertion order is not important

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on