A Guide to LinkedHashSet in Java

1. Overview

in this article, we’ll figure it out linked hashset java class collection API, We will dive into the features of this data structure and demonstrate its functionality.

2. Introduction linked hashset

linked hashset is a generic data structure that deals with java.util Library. it is a direct descendant of hashset Therefore, the data structure contains non-duplicate elements at all times.

Apart from being a doubly-linked list iterating through all its entries, its implementation differs from hashset in that it maintains a predictable iteration order, The iteration order is defined by the insertion order of the elements in the set.

linked hashset Protects the client from unexpected ordering provided hashsetwithout the complexity that comes with a treeset,

whereas Its performance is likely to be slightly lower than hashsetDue to the additional expense of maintaining the linked list, The constant-time (O1) performance for this is add(), include() And Remove() Operation,

3. Create One linked hashset

a. There are many constructors available to create linked hashset, Let’s take a look at each of them:

3.1. default no-arg constructor

Set<String> linkedHashSet = new LinkedHashSet<>();
assertTrue(linkedHashSet.isEmpty());

3.2. build with initial capacity

Represents the initial length of the initial potential linked hashset, Providing initial capacity prevents any unnecessary resizing group as it grows, The default starting capacity is 16:

LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(20);

3.3. a. make from collection

We a. can also use the material of collection to populate linked hashset Object at the point of manufacture:

@Test
 void whenCreatingLinkedHashSetWithExistingCollection_shouldContainAllElementOfCollection(){
      Collection<String> data = Arrays.asList("first", "second", "third", "fourth", "fifth");
      LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(data);
      assertFalse(linkedHashSet.isEmpty());
      assertEquals(data.size(), linkedHashSet.size());
      assertTrue(linkedHashSet.containsAll(data) && data.containsAll(linkedHashSet));
 }

3.4. Build with initial capacity and load factor

size of when linked hashset When the value of the initial capacity exceeds, the new capacity is the multiplication of the load factor and the previous capacity. In the snippet below, the initial capacity is set to 20 and the load factor is 3.

LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(20, 3);

The default load factor is 0.75.

4. Adding an Element to linked hashset

We can either add an element or a collection of elements linked hashset by using add() And Add all() ways respectively. An element will be added if it does not already exist group, these methods return Truth When an element is added to the set, otherwise, they are returned false,

4.1. add a single element

Here is an implementation for adding an element a linked hashset,

@Test
void whenAddingElement_shouldAddElement(){
    Set<Integer> linkedHashSet = new LinkedHashSet<>();
    assertTrue(linkedHashSet.add(0));
    assertFalse(linkedHashSet.add(0));
    assertTrue(linkedHashSet.contains(0));
}

4.2. add one collection of elements

As mentioned earlier, we a. can also add collection elements of a linked hashset,

@Test
void whenAddingCollection_shouldAddAllContentOfCollection(){
    Collection<Integer> data = Arrays.asList(1,2,3);
    LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>();
    assertTrue(linkedHashSet.addAll(data));
    assertTrue(data.containsAll(linkedHashSet) && linkedHashSet.containsAll(data));
 }

The rule of no duplicates also applies to Add all() method As shown below:

@Test
void whenAddingCollectionWithDuplicateElements_shouldMaintainUniqueValuesInSet(){
    LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>();
    linkedHashSet.add(2);
    Collection<Integer> data = Arrays.asList(1, 1, 2, 3);
    assertTrue(linkedHashSet.addAll(data));
    assertEquals(3, linkedHashSet.size());
    assertTrue(data.containsAll(linkedHashSet) && linkedHashSet.containsAll(data));
}

note that information The variable has duplicate values โ€‹โ€‹of 1 and the linked hashset already included Integer Before applying value 2 Add all() way.

5. a . iterate from linked hashset

like every other descendant of collection library, we a. can iterate through linked hashset, There are two types of iterators available in one linked hashset, iterator And spliterator,

Whereas the former only a . is able to traverse and perform any basic operation on collectionthe latter divides collection Performs separate operations on each subset in the subset and in parallel, making it thread-safe,

5.1. an. iterate with iterator

@Test
void whenIteratingWithIterator_assertThatElementIsPresent(){
    LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>();
    linkedHashSet.add(0);
    linkedHashSet.add(1);
    linkedHashSet.add(2);
    Iterator<Integer> iterator = linkedHashSet.iterator();
    for (int i = 0; i < linkedHashSet.size(); i++) {
        int nextData = iterator.next();
        assertEquals(i, nextData);
    }
}

5.2. a. iterate with spliterator

@Test
void whenIteratingWithSpliterator_assertThatElementIsPresent(){
    LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>();
    linkedHashSet.add(0);
    linkedHashSet.add(1);
    linkedHashSet.add(2);
    Spliterator<Integer> spliterator = linkedHashSet.spliterator();
    AtomicInteger counter = new AtomicInteger();
    spliterator.forEachRemaining(data -> {
       assertEquals(counter.get(), (int)data);
       counter.getAndIncrement();
    });
}

6. Remove elements from linked hashset

Here are the different ways to remove an element from linked hashset,

6.1. Remove()

This method removes an element group Given that we know the exact element we want to remove. It accepts an argument which is the actual element we want to remove and returns Truth If successfully deleted, otherwise false,

@Test
void whenRemovingAnElement_shouldRemoveElement(){
    Collection<String> data = Arrays.asList("first", "second", "third", "fourth", "fifth");
    LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(data);
    assertTrue(linkedHashSet.remove("second"));
    assertFalse(linkedHashSet.contains("second"));
}

6.2. remove if()

remove if() The method removes an element that satisfies the specified predicate condition. The example below removes all elements linked hashset which are greater than 2:

@Test
void whenRemovingAnElementGreaterThanTwo_shouldRemoveElement(){
    LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>();
    linkedHashSet.add(0);
    linkedHashSet.add(1);
    linkedHashSet.add(2);
    linkedHashSet.add(3);
    linkedHashSet.add(4);
    linkedHashSet.removeIf(data -> data > 2);
    assertFalse(linkedHashSet.contains(3));
    assertFalse(linkedHashSet.contains(4));
}

6.3. an. deleting with iterator

iterator There is also another option which we can use to remove the elements linked hashset, Remove() method of iterator removes the element that iterator Currently on:

@Test
void whenRemovingAnElementWithIterator_shouldRemoveElement(){
    LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>();
    linkedHashSet.add(0);
    linkedHashSet.add(1);
    linkedHashSet.add(2);
    Iterator<Integer> iterator = linkedHashSet.iterator();
    int elementToRemove = 1;
    assertTrue(linkedHashSet.contains(elementToRemove));
    while(iterator.hasNext()){
        if(elementToRemove == iterator.next()){
           iterator.remove();
       }
    }
    assertFalse(linkedHashSet.contains(elementToRemove));
}

7. Conclusion

In this article, we studied linked hashset data structure from java collection Library. We showed how to make a linked hashset Through its various constructors, adding and removing elements, as well as iterating through it. We also learned about the underlying layers of this data structure, hashset as well as the time complexity for its normal operation.

As always, code snippets can be found on GitHub.

       

Leave a Comment