LinkedHashSet Example in Java

  • LinkedHashSet maintains the elements insertion order.
  • LinkedHashSet extends HashSet and implements the Set interface.
  • LinkedHashSet does not hold any duplicate elements, contains only unique elements like HashSet.
  • LinkedHashSet is non-synchronized.
  • Iterator returned by LinkedHashSet is fail-fast Iterator like HashSet and TreeSet, it will throw ConcurrentModificationException if iterator is modified after it's creation.

In this example we will demonstrate mostly used methods of LinkedHashSet.


import java.util.Iterator;
import java.util.LinkedHashSet;

public class LinkedHashSetExample {
	public static void main(String[] args) {
		// Creating a LinkedHasSet to add strings
		LinkedHashSet<String> myLinkedHashSet = new LinkedHashSet<String>();
		myLinkedHashSet.add("Element1");
		myLinkedHashSet.add("Element2");
		myLinkedHashSet.add("Element3");
		myLinkedHashSet.add("Element4");

		// Printing the elements it contains
		System.out.println(myLinkedHashSet);

		// Iterating each element of myLinkedHashSet using Iterator
		Iterator<String> iterator = myLinkedHashSet.iterator();
		while (iterator.hasNext()) {
			System.out.println(iterator.next());
		}

		// contains method check whether the set contains the specified element
		// or not
		System.out.println(myLinkedHashSet.contains("Element1")); // true
		System.out.println(myLinkedHashSet.contains("Element5"));// false

		
		// Print the size of the set
		System.out.println("size: " + myLinkedHashSet.size());

		// Remove an element from the set
		myLinkedHashSet.remove("Element1");

		System.out.println("After removing Element1 : " + myLinkedHashSet);

		// Removes all of the elements from this set
		myLinkedHashSet.clear();
		System.out.println("After calling clear() : " + myLinkedHashSet);
		
		//isEmpty() Returns true if the set contains no elements.
		System.out.println("is empty :"+myLinkedHashSet.isEmpty());
	}
}
Output
[Element1, Element2, Element3, Element4] Element1 Element2 Element3 Element4 true false size: 4 After removing Element1 : [Element2, Element3, Element4] After calling clear() : [] is empty :true












Related Examples


Write a program to check if an input String is Palindrome or not?
Calculate the factorial of a given number using Java?
How to reverse a number in Java?
Write a program to convert from decimal to binary?
Producer Consumer Example in Thread
Write a program to reverse a String?








Receive Latest Java Examples in Your Email: