StackTips

LinkedHashSet in Java

siteadmin avtar

Written by

Stacktips,  3 min read,  121 views, updated on July 24, 2024

A LinkedHashSet combines the behaviour of both a HashTable and a LinkedList. It extends the HashSet class and implements the Set interface, ensuring that the elements are unique, while also maintaining the insertion order.

Key Properties of LinkedHashSet

HashSet does not guarantee the insertion order but LinkedHashSet maintains the order they are inserted.

For instance, when you need to store unique elements but also need to iterate them in the order they were added, then LinkedHashSet is preferred.

Example: Suppose you are developing a system for tracking user activities on a website. You want to keep track of the unique pages visited by a user in the order they were visited. This can be efficiently managed using a LinkedHashSet.

public class UserActivityTracker {  
    public static void main(String[] args) {  
        LinkedHashSet<String> pagesVisited = new LinkedHashSet<>();  

        pagesVisited.add("home.html");  
        pagesVisited.add("about.html");  
        pagesVisited.add("contact.html");  
        pagesVisited.add("home.html"); 
        pagesVisited.add("services.html");  

        // Display the pages visited in the order of insertion  
        System.out.println("Pages visited by the user in order:");  
        for (String page : pagesVisited) {  
            System.out.println(page);  
        }  

        System.out.println("-----");  
        pagesVisited.spliterator().forEachRemaining(System.out::println);  
    }  
}

Notice that the home.html is added only once to the LinkedHashSet.

Output:

Pages visited:
home.html
about.html
contact.html
services.html

Getting Started with Python - Beginners Guide

Python is a language with a simple syntax and a powerful set of libraries. It is an interpreted language, with a rich programming environment, including a robust debugger and profiler.

>> CHECK OUT THE COURSE

Continue reading..