Curriculum
In Java, LinkedHashSet is a Set implementation that maintains the order of the elements in the set. LinkedHashSet is similar to HashSet, but it uses a linked list to maintain the order of the elements. This makes it slightly slower than HashSet, but faster than TreeSet.
Here’s an example of how to use LinkedHashSet in Java:
import java.util.LinkedHashSet; public class LinkedHashSetExample { public static void main(String[] args) { // create a LinkedHashSet of strings LinkedHashSet<String> set = new LinkedHashSet<>(); // add some elements to the set set.add("apple"); set.add("banana"); set.add("orange"); set.add("banana"); set.add("pear"); // print the set System.out.println(set); } }
Output:
[apple, banana, orange, pear]
In the example above, we create a LinkedHashSet of strings and add some elements to it. Since LinkedHashSet maintains the order of the elements, the output is in the order in which the elements were added to the set.
Here are some of the commonly used methods of LinkedHashSet:
add(E e)
: Adds the specified element to the set.addAll(Collection<? extends E> c)
: Adds all of the elements in the specified collection to the set.remove(Object o)
: Removes the specified element from the set.removeIf(Predicate<? super E> filter)
: Removes all of the elements that satisfy the specified predicate from the set.clear()
: Removes all of the elements from the set.contains(Object o)
: Returns true if the set contains the specified element.isEmpty()
: Returns true if the set contains no elements.size()
: Returns the number of elements in the set.iterator()
: Returns an iterator over the elements in the set.toArray()
: Returns an array containing all of the elements in the set.It’s important to note that LinkedHashSet has the same performance characteristics as HashSet for adding, removing, and checking for the existence of elements. However, since LinkedHashSet maintains the order of the elements, it is slightly slower than HashSet for these operations.