Java Program to add and remove elements from a set which maintains the insertion order

Java 8Object Oriented ProgrammingProgramming

Create a LinkedHashSet −

LinkedHashSet<Integer>set = new LinkedHashSet<Integer>();

Now, add elements to the Set −

set.add(20);
set.add(60);
set.add(80);
set.add(120);
set.add(150);
set.add(200);

For removing the elements −

set.remove(150);
set.remove(260);

Above process of insertion and deletion won’t affect the insertion order.

Example

 Live Demo

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]
raja
Published on 24-Apr-2019 09:13:32
Advertisements