Linked HashSet Class In java

contains unique elements only and It extends HashSet class and implements Set interface

Main Point

  • LinkedHashSet provides collection of unique objects
  • LinkedHashSet is unsorted and non-indexed based collection class
  • Iteration in LinkedHashSet is as per insertion order

LinkedHashSet constructors

LinkedHashSet() // Default constructor

LinkedHashSet(Collection c) // It creates LinkedHashSet from collection c

LinkedHashSet( int capacity) // it creates LinkedHashSet with initial capacity mentioned

LinkedHashSet(int capacity, float loadFactor) // This creates LinkedHashSet with capacity and load factor

Sn Method Purpose
1 public boolean add(Object o) Adds an object to a LinkedHashSet if already not present in
2 HashSet. public boolean remove(Object o) Removes an object from LinkedHashSet if found in HashSet
3 public boolean contains(Object o) Returns true if object found else return false
4 public boolean isEmpty() Returns true if LinkedHashSet is empty else return false
5 public int size() Returns number of elements in the LinkedHashSet

Example of LinkedHash class


				//package linkedHashSet;



import java.util.LinkedHashSet;



public class LinkedHashSetDemo {

public static void main(String[] args) {

LinkedHashSet linkedset = new LinkedHashSet();

// Adding element to LinkedHashSet

linkedset.add("Maruti");

linkedset.add("BMW");

linkedset.add("Honda");

linkedset.add("Audi");

linkedset.add("Maruti"); //This will not add new element as Maruti already exists

linkedset.add("WalksWagon");

System.out.println("Size of LinkedHashSet=" + linkedset.size());

System.out.println("Original LinkedHashSet:" + linkedset);

System.out.println("Removing Audi from LinkedHashSet: " + linkedset.remove("Audi"));

System.out.println("Trying to Remove Z which is not present: "+ linkedset.remove("Z"));

System.out.println("Checking if Maruti is present=" + linkedset.contains("Maruti"));

System.out.println("Updated LinkedHashSet: " + linkedset);
	}
}
		
						
						
						
						
						
						
						

Example

package linkedHashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
	public class LinkedHashSetIterator
	{
	public static void main(String[] args)
	{
	Set myCricketerSet = new LinkedHashSet();
	myCricketerSet.add("Ashwin");
	myCricketerSet.add("Dhoni");
	myCricketerSet.add("Jadeja");
	myCricketerSet.add("Bravo");
	myCricketerSet.add("Hussy");
	myCricketerSet.add("Morkal");
	myCricketerSet.add("Vijay");
	myCricketerSet.add("Raina");

Iterator setIterator = myCricketerSet.iterator();
while(setIterator.hasNext())
{
System.out.println(setIterator.next());
	}
	}
}