Java HashSet: Understanding Unique Collections
Explore the Java HashSet, a part of the java.util package, designed to store unique items efficiently. Learn how HashSet eliminates duplicates, enhances data retrieval, and simplifies collection management in your Java applications.
Java HashSet
A HashSet in Java is a collection where every item is unique, found in the java.util package.
Syntax
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet cars = new HashSet();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("BMW");
cars.add("Mazda");
System.out.println(cars);
}
}
Output
[BMW, Mazda, Ford, Volvo]
HashSet Methods
The HashSet class provides methods to add, check for existence, remove items, and manipulate the set:
add()
: Adds an item to the HashSet.contains()
: Checks if an item exists in the HashSet.remove()
: Removes an item from the HashSet.clear()
: Removes all items from the HashSet.size()
: Returns the number of items in the HashSet.
Loop Through a HashSet
Iterate over a HashSet using a for-each loop to access each item:
Loop Through HashSet
// Print all items in the HashSet
for (String i : cars) {
System.out.println(i);
}
Other Types
HashSet can store objects of different types by specifying appropriate wrapper classes for primitive types:
Example with Integer Values
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
// Create a HashSet object called numbers
HashSet numbers = new HashSet();
// Add values to the set
numbers.add(4);
numbers.add(7);
numbers.add(8);
// Check and print which numbers between 1 and 10 are in the set
for(int i = 1; i <= 10; i++) {
if(numbers.contains(i)) {
System.out.println(i + " was found in the set.");
} else {
System.out.println(i + " was not found in the set.");
}
}
}
}