
Java Hashset in Java
HashSet in Java
A HashSet
is a collection that implements the Set
interface and is part of the java.util
package. It is a collection of unique elements and does not allow duplicates. The HashSet
is backed by a hash table, which makes it efficient for operations like add, remove, and contains.
Key Features of HashSet:
Unordered: A
HashSet
does not maintain any order of its elements. The order can change when elements are added or removed.No duplicates: It does not allow duplicate elements. If you try to add an element that already exists in the set, the add operation will return
false
.Null elements: It allows
null
values, but only onenull
element can be present in the set.Not thread-safe: A
HashSet
is not synchronized, so it's not safe for concurrent modifications. If thread safety is needed, you can useCollections.synchronizedSet()
orConcurrentHashMap
.Faster performance:
HashSet
provides constant time performance (O(1)
) for basic operations like add, remove, and contains.
Creating a HashSet
To create a HashSet
, you need to import it from the java.util
package.
import java.util.HashSet;public class HashSetExample { public static void main(String[] args) { // Create a HashSet of String elements HashSet<String> set = new HashSet<>(); // Adding elements to the HashSet set.add("Apple"); set.add("Banana"); set.add("Orange"); // Printing the HashSet System.out.println(set); }}
Output:
[Apple, Banana, Orange]
(Note: The order may vary because HashSet
is unordered.)
Common HashSet Methods
1. add(E e)
Description: Adds the specified element to the set if it is not already present.
Syntax:
set.add(element);
Example:
set.add("Mango"); // Adds Mango to the set
2. remove(Object o)
Description: Removes the specified element from the set.
Syntax:
set.remove(element);
Example:
set.remove("Banana"); // Removes Banana from the set
3. contains(Object o)
Description: Checks if the specified element is present in the set.
Syntax:
boolean contains = set.contains(element);
Example:
boolean hasApple = set.contains("Apple"); // Returns true
4. size()
Description: Returns the number of elements in the set.
Syntax:
int size = set.size();
Example:
int setSize = set.size(); // Returns the size of the set
5. isEmpty()
Description: Checks if the set is empty.
Syntax:
boolean isEmpty = set.isEmpty();
Example:
boolean empty = set.isEmpty(); // Returns false if the set is not empty
6. clear()
Description: Removes all elements from the set.
Syntax:
set.clear();
Example:
set.clear(); // Clears the HashSet
7. iterator()
Description: Returns an iterator to iterate over the elements in the set.
Syntax:
Iterator<E> iterator = set.iterator();
Example:
Iterator<String> iterator = set.iterator();while (iterator.hasNext()) { System.out.println(iterator.next());}
8. forEach(Consumer<? super E> action)
Description: Performs the specified action for each element in the set.
Syntax:
set.forEach(element -> System.out.println(element));
Example:
set.forEach(element -> System.out.println(element)); // Prints each element in the set
Example: HashSet Operations
import java.util.HashSet;public class HashSetOperations { public static void main(String[] args) { // Create a HashSet of String elements HashSet<String> set = new HashSet<>(); // Adding elements to the HashSet set.add("Apple"); set.add("Banana"); set.add("Orange"); set.add("Apple"); // Duplicate element (will not be added) set.add("Grapes"); // Printing the HashSet System.out.println("Set: " + set); // Checking if an element exists System.out.println("Contains 'Banana': " + set.contains("Banana")); // true System.out.println("Contains 'Mango': " + set.contains("Mango")); // false // Removing an element set.remove("Orange"); System.out.println("After removing 'Orange': " + set); // Getting the size of the set System.out.println("Size of the set: " + set.size()); // Iterating over the set System.out.println("Iterating over set:"); set.forEach(item -> System.out.println(item)); // Clearing the set set.clear(); System.out.println("After clearing, is the set empty? " + set.isEmpty()); }}
Output:
Set: [Apple, Banana, Orange, Grapes]Contains 'Banana': trueContains 'Mango': falseAfter removing 'Orange': [Apple, Banana, Grapes]Size of the set: 3Iterating over set:AppleBananaGrapesAfter clearing, is the set empty? true
Thread-Safe Alternative: ConcurrentHashSet
If thread safety is required, you can use CopyOnWriteArraySet
, which is part of java.util.concurrent
. It's thread-safe but comes with a slight performance overhead for write operations.
HashSet vs TreeSet vs LinkedHashSet
HashSet
: Does not maintain any order of elements.LinkedHashSet
: Maintains the insertion order of elements.TreeSet
: Stores elements in a sorted order (natural ordering or using a comparator).
Conclusion
The HashSet
is an efficient and commonly used collection when you need to store unique elements without caring about the order. Its constant time complexity for adding, removing, and checking for elements makes it suitable for many scenarios where performance is critical. However, remember that it doesn't maintain any order.
If you need further clarification or examples, feel free to ask! ?