Java HashSet Class Methods

The HashSet class in Java is a part of the Java Collections Framework and implements the Set interface. The HashSet class uses a hash table for storage and does not allow duplicate elements. HashSet is widely used when you want to store unique elements and don’t care about the order.

This guide covers various methods available in the HashSet class, offering a comprehensive understanding of how to manipulate and interact with sets in Java. These methods are essential for efficient coding practices and help in performing operations like adding, removing, and checking for elements.

For more detailed information, you can refer to the official Java SE Documentation and additional resources on Java Collections Tutorial.

Java HashSet Class Methods

Method Description
add() Adds an element to the HashSet if it is not already present.
clear() Removes all elements from the HashSet.
clone() Creates a shallow copy of the HashSet.
isEmpty() Checks if the HashSet is empty.
iterator() Returns an iterator over the elements in the HashSet.
newHashSet() Creates a new, empty HashSet.
remove() Removes a specified element from the HashSet.
size() Returns the number of elements in the HashSet.
spliterator() Creates a Spliterator over the elements in the HashSet.
toArray() Returns an array containing all elements in the HashSet.
addAll() Adds all elements from another collection to the HashSet.
containsAll() Checks if the HashSet contains all elements from another collection.
removeAll() Removes all elements that are also in another collection from the HashSet.
retainAll() Keeps only the elements that are also in another collection in the HashSet.
stream() Returns a stream of the elements in the HashSet.
parallelStream() Returns a parallel stream of the elements in the HashSet.
removeIf() Removes all elements that satisfy a specified condition.
forEach() Performs an action for each element in the HashSet.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top