Remove all elements from Java LinkedHashSet


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("
Updated LinkedHashSet..."); System.out.println(hashSet); } }

Output

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

Updated LinkedHashSet...
[]

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

249 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements