HashSet in java
HashSet used to store the data and Its remove Duplicate data.The data stored in Hashtable.
Add
import java.util.HashSet; public class Main { public static void main(String[] args) { HashSet<Integer> num = new HashSet<Integer>(); num.add(1); num.add(2); num.add(3); num.add(1); System.out.print(num); } }
Output
[1, 2, 3]
Contains
import java.util.HashSet; public class Main { public static void main(String[] args) { HashSet<Integer> num = new HashSet<Integer>(); num.add(1); num.add(2); num.add(3); System.out.print(num.contains(1)); } }
Output
true
Remove
import java.util.HashSet; public class Main { public static void main(String[] args) { HashSet<Integer> num = new HashSet<Integer>(); num.add(1); num.add(2); num.add(3); num.remove(1); System.out.print(num); } }
Output
[2, 3]
Size
import java.util.HashSet; public class Main { public static void main(String[] args) { HashSet<Integer> num = new HashSet<Integer>(); num.add(1); num.add(2); num.add(3); System.out.print(num.size()); } }
Output
3
Clear
import java.util.HashSet; public class Main { public static void main(String[] args) { HashSet<Integer> num = new HashSet<Integer>(); num.add(1); num.add(2); num.add(3); num.clear(); System.out.print(num); } }
Output
[]
print each element:
import java.util.HashSet; public class Main { public static void main(String[] args) { HashSet<Integer> num = new HashSet<Integer>(); num.add(1); num.add(2); num.add(3); for(int i : num) { System.out.println(i); } } }
Output
1 2 3
String:
Add
import java.util.HashSet; public class Main { public static void main(String[] args) { HashSet<String> names = new HashSet<String>(); names.add("jack"); names.add("stark"); names.add("steve"); System.out.println(names); } }
Output
[stark, steve, jack]