LinkedHashSet in Java, Linked Hashset, LinkedHashset collection in java


We will cover following points of LinkedHashset in Java:

  1. Basics of LinkedHashset in Java
  2. How to iterate through LinkedHashset in Java
  3. Constructor and methods of LinkedHashset in Java

Basics of LinkedHashset in Java

  1. LinkedHashSet is a class which extends HashSet class and implements Set, Cloneable, Serializable interface.
  2. LinkedHashSet doesn’t allow duplicate elements.
  3. It uses node representation to store the elements.
  4. We can have null in LinkedHashSet.
  5. It maintains insertion order.
  6. LinkedHashSet elements can be iterated through Iterator and for-each loop only, it can’t be accessed using ListIterator and Enumeration interface.
  7. LinkedHashSet methods are not synchronized.

How to iterate LinkedHashset in Java

  1. Using iterator
import java.util.LinkedHashSet;
import java.util.Set;

public class IterateLinkedHashSet {
       public static void main(String[] args) {
              Set linkedHashSetObj = new LinkedHashSet();
                  linkedHashSetObj.add("nadeem");
                  linkedHashSetObj.add("shyam");
                  linkedHashSetObj.add("puneet");
                  linkedHashSetObj.add("nadeem");
                  linkedHashSetObj.add("nadeem");

                  Iterator it = linkedHashSetObj.iterator();
                  while (it.hasNext()) {
                         System.out.println(it.next());
                  }
         }
 }
Nadeem
Puneet
Shyam
  1. Using for each
import java.util.Set;

public class ForEachLinkedHashSet {
       public static void main(String[] args) {
              Set<String> linkedHashSetObj = new LinkedHashSet();
                          linkedHashSetObj.add("nadeem");
                          linkedHashSetObj.add("shyam");
                          linkedHashSetObj.add("puneet");
                          linkedHashSetObj.add("nadeem");
                          linkedHashSetObj.add("nadeem");
                          for (String str : linkedHashSetObj) {
                               System.out.println(str);
                          }
              }
  }
Nadeem
Puneet
Shyam

Constructor and methods of LinkedHashSet in Java

LinkedHashSetin Java has mainly 2 constructor:

  • LinkedHashSet()
  • LinkedHashSet(Collection c)
  • LinkedHashSet(int initialCapacity)
  • LinkedHashSet(int initialCapacity, float loadFactor)

Learn more about collection in java


%d bloggers like this: