HashSet implements the Set interface and inherits the AbstratSet class in Java that uses a HashTable for storage. HashSet applies the random order of the elements. Here, In this post, we will see an example on how to create a HashSet in java and how to iterates its data.
Simplest Presentation of Java HashSet Share on X
Points to remember:
- HashSet elements would get returned in any random order.
- Java HashSet won’t return duplicate elements as If there is a duplicate element in the HashSet then the old value would be overwritten.
- Java HashSet is non-synchronized.
- HashSet allows null values.
Syntax:
HashSet<Integer> hashSet = new HashSet<>();
Note: In below example 1, we are creating HashSet of type Integer and in example 2, it’s of String.
Example 1
import java.util.HashSet;
public class HashSetIntegerSample {
public static void main(String[] args) {
HashSet < Integer > hashSetInteger = new HashSet < > ();
hashSetInteger.add(107);
hashSetInteger.add(90);
hashSetInteger.add(35);
hashSetInteger.add(95);
hashSetInteger.add(5);
hashSetInteger.add(90);
for (int hsi: hashSetInteger) {
System.out.println(hsi);
}
}
}
Output 1:
35 5 90 107 95
Note: it could come to a different order for everyone.
Example 2
import java.util.HashSet;
public class HashSetStringSample {
public static void main(String[] args) {
HashSet < String > hashSetString = new HashSet < > ();
hashSetString.add("Yogi");
hashSetString.add("Gaurangee");
hashSetString.add("Pulkit");
hashSetString.add("Isha");
hashSetString.add("Yash");
hashSetString.add("Yash");
hashSetString.add("Deepak");
for (String hss: hashSetString) {
System.out.println(hss);
}
}
}
Output 2:
Isha Yogi Yash Pulkit Gaurangee Deepak
If you like this post, please check out my other similar posts:
HashTable in Java with Example
Hello. I have checked your techndeck.com and i see you’ve got some duplicate content so probably
it is the reason that you don’t rank high in google.
But you can fix this issue fast. There is a tool that generates content like human, just search in google: miftolo’s tools
thank you MauricioBig