Java LinkedHashSet

Java LinkedHashSet extends HashSet class and implements Set interface.

 LinkedHashSet maintains the insertion order. 

LinkedHashSet stores only unique entries like HashSet.

LinkedHash is not synchronized and thread safe.

HashSet: doesn’t maintain any order.

TreeSet: sort elements in ascending order.

LinkedHashSet: maintains the insertion order.

Syntax:

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

Constructors:

Below are the constructor to create LinkedHashSet object.

LinkedHashSet() → The below expression will create empty LinkedHashSet.

LinkedHashSet linkedHashSet = new LinkedHashSet();

LinkedHashSet(Collection c) → The below expression will create LinkedHashSet with other collections.

LinkedHashSet linkedHashSet = new LinkedHashSet(Collection c);

LinkedHashSet(int size) → The below expression will create LinkedHashSet with some size.

LinkedHashSet linkedHashSet = new LinkedHashSet (int size);

LinkedHashSet(int initialCapacity, int loadFactor) → The below expression will initialize LinkedHashSet with some initial capacity and load factor.

LinkedHashSet linkedHashSet = new LinkedHashSet (int initialCapacity, int loadFactor);

Example:

Below is the simple example to create LinkedHashSet, add elements in to it and print on the screen.

LinkedHashSet Methods:

Below are some of the methods from LinkedHashSet class.

add(): Method helps us to add an element in LinkedHashSet.

remove(): Method helps us to remove an element from LinkedHashSet.

size(): Method returns the number of element in LinkedHashSet Collection.

remove(): Method helps us to remove an element from LinkedHashSet.

contains(): Method returns true if specified element present in LinkedHashSet collection else return false.

clear(): Method helps us to remove all the elements from LinkedHashSet.

isEmpty(): Method returns true if number of elemetns is zero else return false.

OUTPUT:

Imran Khan

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan