Add and Remove Elements from a Set Maintaining Insertion Order in Java



In this article, we will learn how to use a LinkedHashSet in Java to add and remove elements while maintaining the insertion order. You will see how elements are stored, removed, and updated in a LinkedHashSet without altering the sequence in which they were added.

Problem Statement

Write a Java program to add elements to a LinkedHashSet, remove specific elements, and display the updated set while ensuring the insertion order of the elements remains unchanged. Below is a demonstration of the same ?

Input

Set = [20, 60, 80, 120, 150, 200, 220, 260, 380]

Output

Set = [20, 60, 80, 120, 150, 200, 220, 260, 380]
Updated Set = [20, 60, 80, 120, 200, 220, 380]
Updated Set = [20, 80, 120, 200, 220, 380]

Steps to add and remove elements from a set

Following are the steps to add and remove elements from a set ?

  • Import the LinkedHashSet class from the java.util package.
  • Create a LinkedHashSet to store integer elements.
  • Add multiple integers to the LinkedHashSet.
  • Print the set to display the elements in the order they were inserted.
  • Remove specific elements from the set using the remove() method.
  • Print the set after each removal to show the updated set while maintaining the insertion order.

Java program to add and remove elements from a set

Below is the example of adding and removing elements from a set which maintains the insertion order ?

import java.util.LinkedHashSet;
public class Demo {
   public static void main(String[] args) {
      LinkedHashSet<Integer>set = new LinkedHashSet<Integer>();
      set.add(20);
      set.add(60);
      set.add(80);
      set.add(120);
      set.add(150);
      set.add(200);
      set.add(220);
      set.add(260);
      set.add(380);
      System.out.println("Set = "+set);
      set.remove(150);
      set.remove(260);
      System.out.println("Updated Set = "+set);
      set.remove(60);
      System.out.println("Updated Set = "+set);
   }
}

Output

Set = [20, 60, 80, 120, 150, 200, 220, 260, 380]
Updated Set = [20, 60, 80, 120, 200, 220, 380]
Updated Set = [20, 80, 120, 200, 220, 380]

Code explanation

The program uses a LinkedHashSet to store integers, which preserves the order of insertion. Elements are added using the add() method and removed using the remove() method. After each modification, the set is printed to show the updated state while ensuring the original insertion order remains intact.

Updated on: 2024-11-19T18:23:22+05:30

516 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements