HashSet In Java
There is a discussion of Java Hashset to better meet the learners’ needs.
Java HashSet
When it comes to Java HashSet, a HashSet consists of items that are all unique, and it is part of the java.util package.
A HashSet object will be created for storing strings and will be named as programming_language:
import java.util.HashSet; // Here we have imported the class named as HashSet from java.util package
public class Main {
public static void main(String[] args) {
HashSet programming_languages=new HashSet();
}
}
Similarly, here we create another HashSet object and name it as “NFL_teams”:
import java.util.HashSet; // Here we have imported the class named as HashSet from java.util package
public class Main {
public static void main(String[] args) {
HashSet nfl_Teams=new HashSet();
}
}
Java HashSet Add()
Many useful methods are available in the HashSet class. As an example, add() allows you to add items:
We have used the add() method in order to insert elements to the HashSet object named as programming_languages as shown in the example below:
import java.util.HashSet; // Here we have imported the class named as HashSet from java.util packagepublic class Main {
public static void main(String[] args) {HashSet programming_languages=new HashSet();
programming_languages.add("Java");
programming_languages.add("Python");
programming_languages.add("C language");
programming_languages.add("C# programming language");
programming_languages.add("Java");System.out.println(programming_languages);}
}
Likewise, the given example also adds names of the nfl teams to the HashSet object named as nfl_Teams using the add() method.
import java.util.HashSet; // Here we have imported the class named as HashSet from java.util packagepublic class Main {
public static void main(String[] args) {HashSet nfl_Teams=new HashSet();
nfl_Teams.add("Arizona Cardinals");
nfl_Teams.add("Atlanta Falcons");
nfl_Teams.add("Cincinnati Bengals");
nfl_Teams.add("Baltimore Ravens");
nfl_Teams.add("Atlanta Falcons");System.out.println(nfl_Teams);}
}
Reminder: In the examples above, even though “Java” appears twice in the first example, and “Atlanta Falcons” is repeated again in the second, yet they only appear once in each set as according to the property of HashSet each set should contain all all unique elements.
Java HashSet Contains()
It is possible to check the existence of an item in a HashSet by using the contains() method.
Using the contain() method we can determine if the string is a part of HashSet or not , as shown in the example below:
import java.util.HashSet; // HashSet class is imported herepublic class Main {
public static void main(String[] args) {
HashSet sports_players = new HashSet(); // The object of HashSet is created here.sports_players.add("Cristiano Ronaldo");
sports_players.add("Sachin Tendulkar");
sports_players.add("Wayne Gretzky");
sports_players.add("Babe Ruth");
sports_players.add("Jonah Lomu");System.out.println(sports_players.contains("Sachin Tendulkar")); // Result as true as string Sachin Tendulkar is a part of the HashSet}
}
Now putting the string value to “Virat Kohli” in order to check if it exists in the HashSet or not :
import java.util.HashSet; // HashSet class is imported herepublic class Main {
public static void main(String[] args) {
HashSet sports_players = new HashSet(); // The object of HashSet is created here.sports_players.add("Cristiano Ronaldo");
sports_players.add("Sachin Tendulkar");
sports_players.add("Wayne Gretzky");
sports_players.add("Babe Ruth");
sports_players.add("Jonah Lomu");
System.out.println(sports_players.contains("Virat Kohli")); // Shows output as false, as string Virat Kohli is not a part of the given HashSet}
}
Java HashSet Remove() and Clear()
As with Java HashMap and ArrayList, you can delete an item using the remove() method:
The given example shows the removal of number 2 from the HashSet object named “numbers”:
import java.util.HashSet; // HashSet class is imported herepublic class Main {
public static void main(String[] args) {
HashSet numbers = new HashSet(); // The object of HashSet is created here and its datatype is Integer.numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);numbers.remove(2); // Number 2 is removed from the HashSetSystem.out.println(numbers);}
}
import java.util.HashSet; // HashSet class is imported herepublic class Main {
public static void main(String[] args) {
HashSet heights_record = new HashSet(); // The object of HashSet is created here having the datatype float.heights_record.add(5.6f);
heights_record.add(6.1f);
heights_record.add(5.3f);
heights_record.add(6.11f);
heights_record.add(5.2f);heights_record.remove(6.11f); // the height 6.11 is removed from the HashSetSystem.out.println(heights_record);}
}
To empty the HashSet, use the clear() method:
import java.util.HashSet; // Here we have imported the class named as HashSet from java.util packagepublic class Main {
public static void main(String[] args) {HashSet mlb_Teams=new HashSet();
mlb_Teams.add("Miami Marlins");
mlb_Teams.add("Atlanta Braves");
mlb_Teams.add("NewYork Mets");
mlb_Teams.add("Philadelphia Phillies");
mlb_Teams.add("Washington Nationals");System.out.println("\nBefore using the clear method: "+mlb_Teams);mlb_Teams.clear(); // Clear method is used here which makes the HashSet emptySystem.out.println("\nAfter using the clear method: "+mlb_Teams);
}
}
import java.util.HashSet; // Here we have imported the class named as HashSet from java.util packagepublic class Main {
public static void main(String[] args) {HashSet sports_Cars=new HashSet();
sports_Cars.add("Mazda MX-5 Miata");
sports_Cars.add("Subaru BRZ");
sports_Cars.add("Toyota GR86");
sports_Cars.add("Supra");
sports_Cars.add("Chevy Camaro ZL1");System.out.println("\nBefore using the clear method: "+sports_Cars);sports_Cars.clear(); // Clear method is used here which makes the HashSet emptySystem.out.println("\nAfter using the clear method: "+sports_Cars);
}
}
Java HashSet Size()
Use the size() method to determine the number of elements in the HashSet:
Following example calculates the number of elements from the HashSet named as nba_Teams using the size() method:
import java.util.HashSet; // Here we have imported the class named as HashSet from java.util packagepublic class Main {
public static void main(String[] args) {HashSet nba_Teams=new HashSet();nba_Teams.add("Boston Celtics");
nba_Teams.add("Chicago Bulls");
nba_Teams.add("Atlanta Hawks ");
nba_Teams.add("Brooklyn Nets");
nba_Teams.add("Cleveland Cavaliers");System.out.println("The HashSet contains "+nba_Teams.size()+" elements");}
}
import java.util.HashSet; // Here we have imported the class named as HashSet from java.util packagepublic class Main {
public static void main(String[] args) {HashSet laptop_brands= new HashSet();laptop_brands.add("Dell");
laptop_brands.add("Hp");
laptop_brands.add("Samsung");
laptop_brands.add("Asus");
laptop_brands.add("Acer");System.out.println("The size of the given HashSet is: "+laptop_brands.size());}
}
Loop Through HashSet
Using a for-each loop, we can traverse through the items of a HashSet.
Here we use a for-each loop to print all the elements from the HashSet named as “alphabets”:
import java.util.HashSet; // Here we have imported the class named as HashSet from java.util packagepublic class Main {
public static void main(String[] args) {HashSet alphabets=new HashSet();alphabets.add('A');
alphabets.add('B');
alphabets.add('C');
alphabets.add('D');
alphabets.add('E');System.out.println("Using the for-each loop to print elements of the HashSet named alphabets: ");for (char mrx:alphabets) {
System.out.println(mrx);
}
}
}
import java.util.HashSet; // Here we have imported the class named as HashSet from java.util packagepublic class Main {
public static void main(String[] args) {HashSet billionaires =new HashSet();billionaires.add("Bernard Arnault");
billionaires.add("Elon Musk");
billionaires.add("Gautam Adani");
billionaires.add("Bill Gates");
billionaires.add("Jeff Bezos");for(String ample :billionaires ) {
System.out.println(ample);
}
}
}
Other Types
HashSets are actually collections of objects. Based on the examples above, we have built elements (objects) of types “String” “int” “float” and “char”.
You should remember that in Java, the String type is an object (not a primitive type). It is necessary to specify an equivalent wrapper class for other types, such as int , char , float , boolean, and double, which is Integer , Character , Float, Boolean and Double.
If you want to store double values in a HashSet, follow the example below:
import java.util.HashSet; // Here we have imported the class named as HashSet from java.util packagepublic class Main {
public static void main(String[] args) {HashSet double_numbers =new HashSet(); // Here we use double data type and utilized the wrapper class Doubledouble_numbers.add(1412.541231d);
double_numbers.add(2312.41412d);
double_numbers.add(5345.234234d);
double_numbers.add(623.6345324d);
double_numbers.add(854.6524423d);for(double mrx :double_numbers ) {
System.out.println("Value : "+mrx);
}
}
}
Correspondingly, we can use the boolean data type by referring to its wrapper class Boolean to create the following HashSet:
import java.util.HashSet; // Here we have imported the class named as HashSet from java.util packagepublic class Main {
public static void main(String[] args) {HashSet boolean_Values =new HashSet(); // Here we use boolean data type and utilized the wrapper class Booleanboolean_Values.add(false);
boolean_Values.add(true);
boolean_Values.add(false);
boolean_Values.add(true);
boolean_Values.add(false);
boolean_Values.add(false);
boolean_Values.add(false);for (boolean mr_x:boolean_Values) {
System.out.println(mr_x); // Only different values are printed even there are repeated values in this code which satisfies the property of the HashSet to show unique elements only
}
}
}
Here are some key points about Java HashSet:
- An element in a HashSet is stored by hashing.
- There are only unique elements in a HashSet.
- Null values are allowed in HashSets.
- The HashSet class is not synchronized.
- The insertion order is not maintained by HashSet.
- Elements are inserted based on their hashcodes.
- Search operations are best performed using HashSets.
- HashSet’s default capacity is 16, and its load factor is 0.75.