Remove all elements from Java LinkedHashSet

Java 8Object Oriented ProgrammingProgramming

To remove all the elements from LinkedHashSet in Java, use the clear() method.

The following is an example to declare LinkedHashSet and add elements to it −

LinkedHashSet<Integer> hashSet = new LinkedHashSet<Integer>();
hashSet.add(10);
hashSet.add(20);
hashSet.add(30);
hashSet.add(40);
hashSet.add(50);
hashSet.add(60);

Use the clear() method to remove all elements −

hashSet.clear();

The following is an example −

Example

 Live Demo

import java.util.LinkedHashSet;
public class Demo {
   public static void main(String[] args) {
      LinkedHashSet<Integer> hashSet = new LinkedHashSet<Integer>();
      hashSet.add(10);
      hashSet.add(20);
      hashSet.add(30);
      hashSet.add(40);
      hashSet.add(50);
      hashSet.add(60);
      System.out.println("LinkedHashSet...");
      System.out.println(hashSet);
      // cleared the set
      hashSet.clear();
      System.out.println("\nUpdated LinkedHashSet...");
      System.out.println(hashSet);
   }
}

Output

LinkedHashSet...
[10, 20, 30, 40, 50, 60]

Updated LinkedHashSet...
[]
raja
Published on 11-Jan-2019 10:05:48
Advertisements