LinkedHashSet – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sat, 15 Jul 2023 13:56:36 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg LinkedHashSet – Programmerbay https://programmerbay.com 32 32 LinkedHashSet Class in Java With Program Example https://programmerbay.com/linkedhashset-class-in-java-with-program-example/ https://programmerbay.com/linkedhashset-class-in-java-with-program-example/#respond Sat, 15 Jul 2023 13:56:36 +0000 https://programmerbay.com/?p=9406 LinkedHashet is an implementation class of the Set interface which also extends the HashSet class. It was introduced in Java 1.4 version. It behaves in the same manner as HashSet except that it preserves or maintains the insertion order of elements inserted in the set. In simple words, It is an implementation of the set interface that stores and manipulates an ordered collection of elements.
It simply means the order in which elements are inserted, can be retrieved in the same order.

Screenshot from 2023 07 10 23 23 20

Points to Remember:

1) Hash Table and Linked List are its underlying data structure

2) It extends HashSet class and implements Set interface
3) It preserves insertion order
4) It permits only unique elements, similar to HashSet
5) It allows at most single null value
6) It offers a constant time performance for all the basic operations
7) It is less expensive than HashSet when comes to iterating over elements

Syntax:

Set<T> set = new LinkedHashSet<T>();

It is an implementation class that uses hash table and linked list data structure as its underlying data structure. It differs from HashSet with the exception that it maintains a doubly linked list to all the elements. It preserves insertion order with the help of a linked list which defines iteration order and makes sure the elements must be retrieved in the same order as they were previously inserted. It allows a single null element. It provides constant time performance for the basic operations.

There are 4 constructors provided in LinkedHashSet class:

1) LinkedHashSet()

A default constructor to create an empty linked hash set with default initial capacity and load factor.

LinkedHashSet<T> linkedHashSet = new LinkedHashSet<T>();

2) LinkedHashSet(collectionObj) 

It creates a new linked hash set having elements present in passed collection object.

ArrayList<T> list = new ArrayList<>();

LinkedHashSet<T> linkedHashSet = new LinkedHashSet<T>(list);

3) LinkedHashSet(int initialCapacity) :

It creates an empty linked hash set with specified capacity and default load factor.

LinkedHashSet<T> linkedHashSet = new LinkedHashSet<T>(4);

4) LinkedHashSet(int initialCapacity, float loadFactor):

It creates an empty linked hash set with mentioned capacity and load factor.

LinkedHashSet<T> linkedHashSet = new LinkedHashSet<T>(4,0.8);

Methods of LinkedHashSet Class

Method NameExplanation
add(Object)The method adds an element in a given set, returns false if one tries to add duplicate element
addAll(CollectionObj)It adds all the elements of the given collection in a given set
clear()It removes all elements from the given set
contains(Object)It checks whether the given object consists in a set or not, if it returns true if exist, otherwise false
containsAll(CollectionObj)It returns true, if all the elements of the given collection exist in the set, otherwise false
isEmpty()It checks whether a set is empty or not. it returns if empty, other false
iterator()It provides iterator object to iterate through set
remove(Object)It removes the given object from the set, if present
retainAll(CollectionObj)It retains elements of the collection provided in the method, and removed all other elements in the set that don't match the elements of collection object
size()It returns number of elements present in a set
spliterator()it returns spliterator object to iterate through set
toArray()It converts given set and returns array
removeAll(CollectionObj)It removes all the elements consisting in the collection object

Java Program to create LinkedHashSet instance and demonstrate its basic operations

Program:

import java.util.*;

public class SetExample {
    public static void main(String[] args) {

        Set<Integer> linkedHashSet = new LinkedHashSet<>(); // creating a linked hashset instance that holds integers

        // Adding elements to linked hash set
        linkedHashSet.add(5);
        linkedHashSet.add(1);
        linkedHashSet.add(null);  // adding nul value
        linkedHashSet.add(100);

        // Displaying Stored elements
        System.out.println(linkedHashSet);

        // removing null element from linked hash set

        linkedHashSet.remove(null);

        //Displaying after removing null

        System.out.println(linkedHashSet);

        // iterating through hash set

        Iterator iterator = linkedHashSet.iterator(); // getting iterator object
        System.out.println("Iterating over all the element of linked hash set :: ");
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }


    }
}

Output:

[5, 1, null, 100]
[5, 1, 100]
Iterating over all the element of linked hash set :: 
5
1
100

Basic Operations of LinkedHashSet

1) Adding element

HashLinkedSet supports add() and addAll() method to add elements in a given set

add(element) : It adds a given element to the set
addAll(collectionObj): It adds all the elements provided in collection object.

Java program to demonstrate add operation in LinkedHashSet

Program:

import java.util.*;

public class SetExample {
public static void main(String[] args) {

Set<Integer> linkedHashSet = new LinkedHashSet<>(); // creating a linked hashset instance that holds integers

// Adding elements to linked hash set
linkedHashSet.add(5);
linkedHashSet.add(1);

// Displaying Stored elements
System.out.println(linkedHashSet);

// add All method to add multiple elements

linkedHashSet.addAll(Arrays.asList(100,101,102,103));

//Displaying after addAll

System.out.println(linkedHashSet);


}
}

Output:

[5, 1]
[5, 1, 100, 101, 102, 103]

2) Removing element

There are two methods namely, remove() and removeAll() used for removing single or multiple elements from a set.
remove(element) : It removes the given element from the given set.
remove(collectionObj) : It removes all the elements present in the collection object from the given set.

Java program to demonstrate remove operation in LinkedHashSet

Program:

import java.util.*;

public class SetExample {
public static void main(String[] args) {

Set<Integer> linkedHashSet = new LinkedHashSet<>(); // creating a linked hashset instance that holds integers

// Adding elements to linked hash set
linkedHashSet.add(5);
linkedHashSet.add(1);

linkedHashSet.add(2);
linkedHashSet.add(100);
linkedHashSet.add(101);
linkedHashSet.add(102);
// Displaying Stored elements
System.out.println(linkedHashSet);

// removing single element the linked hash set

linkedHashSet.remove(2);

System.out.println("Removed 2 :: "+linkedHashSet);

// removeAll for remove multiple elements

linkedHashSet.removeAll(Arrays.asList(100,101,102));

//Displaying after removeAll

System.out.println("Removed 100, 101,102 from set :: "+linkedHashSet);


}
}

Output:

[5, 1, 2, 100, 101, 102]
Removed 2 :: [5, 1, 100, 101, 102]
Removed 100, 101,102 from set :: [5, 1]

3) Iterating over elements

There are multiple ways to iterate over a linked hash set. These are the following :-
1) iterator()
2) forEach()
3) Using Java 8 streams

Java program to demonstrate iteration operation over elements of a linked hash set object

Program:

import java.util.*;

public class SetExample {
public static void main(String[] args) {

Set<Integer> linkedHashSet = new LinkedHashSet<>(); // creating a linked hashset instance that holds integers

// Adding elements to linked hash set
linkedHashSet.add(5);
linkedHashSet.add(1);

linkedHashSet.add(2);
linkedHashSet.add(100);
linkedHashSet.add(101);

// Iterating using for each

System.out.println("Iterating using foreach :: ");
for (Integer element:
linkedHashSet) {
System.out.println(element);
}

// Iterating using iterator object
System.out.println("Iterating using iterator :: ");

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

System.out.println("Iterating using stream :: ");

linkedHashSet.stream().forEach(e-> System.out.println(e));
}
}

 

Output:

Iterating using foreach ::
5
1
2
100
101
Iterating using iterator ::
5
1
2
100
101
Iterating using stream ::
5
1
2
100
101

 

]]>
https://programmerbay.com/linkedhashset-class-in-java-with-program-example/feed/ 0