Create LinkedHashSet in Java - How to Add Elements to LinkedHashset
Learn how HashTables and LinkedHashSets work together in Java to ensure elements are stored in order with hash tables at rrtutors.com Check it out!
To create a LinkedHashSet set, you first need to import the Java.util.LinkedHashSet package in your Java program. After you have imported the package, now you can create a LinkedHashSets using the Syntax below:
LinkedHashSet<Integer> sample = new LinkedHashSet<> |
This syntax has two parameters. The first parameter is the capacity, and the second parameter is the LoadFactor.
The Methods Supported by The LinkedHashSet
The LinkedHashSet class provides a number of methods that enable various operations to be performed on a linked Hash Set. These methods include:
-
remove()- The element specified will be removed from LinkedHashSet using this method.
-
removeAll()- This method removes all values from LinkedHashSet
-
addAll()- Performs a union between two sets
-
retainAll()- This method Intersects the two sets
-
next()-returns the next elements in the LinkedHashSet
-
hasNext()- returns true whenever there is a next element in the LinkedHashSet
-
add()- inserts a specific element into the LinkedHashSet
-
addAll()- inserts all the elements of the specified collection of the LinkedHashSet.
Add Elements to LinkedHashSet
In this example, we are going to insert an element into the LinkedHashSet.
import java.util.LinkedHashSet; public class LinkedHashExample { public static void main(String[] args) { LinkedHashSet<Integer> originalLHS = new LinkedHashSet<>(); // Create a LinkedHashExample using add() method originalLHS.add(1); originalLHS.add(2); originalLHS.add(3); System.out.println("Original LinkedHashSet: " + originalLHS); LinkedHashSet<Integer> AddedLHS = new LinkedHashSet<>(); // Now we add a new element Using addAll() method AddedLHS.addAll(originalLHS); AddedLHS.add(4); System.out.println("New LinkedHashSet After Inserting Element: " + AddedLHS); } } |
Output:
Original LinkedHashSet: [1, 2, 3]
New LinkedHashSet After Inserting Element: [1, 2, 3, 4]