Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Java - Remove from Set


As we have seen the implementations of a Set are :

  1. HashSet

  2. LinkedHashSet


Let us see the HashSet implementation,


How to remove an element from the HashSet by its name/value?


Let us say, we have a HashSet that contains three names, Mohan, Kriti and Salim. And we want to remove Kriti from the HashSet.


It can be done with the Remove() method.


Example :



import java.util.*;

public class MyApplication {
    public static void main(String[] args) {

        Set x = new HashSet<>();

        x.add("Mohan");
        x.add("Kriti");
        x.add("Salim");

        x.remove("Kriti");

        for (String i : x) {
            System.out.println(i);
        }
    }
}


Output :



  Mohan
  Salim

So, in the above code we have created a HashSet and initialised to the variable x.


Set x = new HashSet<>();

x.add("Mohan");
x.add("Kriti");
x.add("Salim");

Below is how the values are positioned in the HashSet,

Spring_Boot

Next, we have used the remove() method that searches for the name Kriti and removes it from the HashSet.


x.remove("Kriti")
Spring_Boot


And we get the below output,

Output :



  Mohan
  Salim

How to remove all the elements from the HashSet?


The clear() Method can be used to remove all the elements from the HashSet.


Example :



import java.util.*;

public class MyApplication {
    public static void main(String[] args) {

        Set x = new HashSet<>();

        x.add("Mohan");
        x.add("Kriti");
        x.add("Salim");

        x.clear();

        for (String i : x) {
            System.out.println(i);
        }
    }
}


Output :




So, in the above code we have created a HashSet and initialised to the variable x.


Set x = new HashSet<>();

x.add("Mohan");
x.add("Kriti");
x.add("Salim");

Below is how the values are positioned in the HashSet,

Spring_Boot

Next, we have used the clear() method that removes all the elements from the HashSet making the HashSet empty.


And we get an empty HashSet as output.


Note : The same code applies for LinkedHashSet as well. Just that you need to replace HashSet with LinkedList.

Example :



import java.util.*;

public class MyApplication {
    public static void main(String[] args) {

        Set x = new LinkedHashSet<>();

        x.add("Mohan");
        x.add("Kriti");
        x.add("Salim");

        x.clear();

        for (String i : x) {
            System.out.println(i);
        }
    }
}


Output :