The HashSet
class in Java is part of the Java Collections Framework and implements the Set
interface, backed by a hash table (actually a HashMap
instance). It does not allow duplicate elements and provides constant-time performance for basic operations like add, remove, contains, and size, assuming the hash function disperses the elements properly among the buckets. This tutorial will cover all the methods of the HashSet
class with examples and outputs.
Table of Contents
- Introduction
- Key Points About
HashSet
Class - Methods
add
addAll
clear
clone
contains
containsAll
isEmpty
iterator
remove
removeAll
retainAll
size
toArray
spliterator
stream
parallelStream
removeIf
forEach
- Conclusion
Introduction
The HashSet
class in Java is widely used for storing unique elements. It provides a powerful and flexible way to manage collections of objects. Here are some key points about the HashSet
class:
- No Duplicates:
HashSet
does not allow duplicate elements. If you try to add a duplicate element, it will not be added to the set. - Order:
HashSet
makes no guarantees about the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. - Null Elements:
HashSet
allows null elements. - Performance:
HashSet
provides constant-time performance for the basic operations (add, remove, contains, and size).
Methods
add() Method
The add
method is used to add a specified element to the set if it is not already present.
Syntax
public boolean add(E e)
Example
import java.util.HashSet;
public class HashSetAddExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
set.add("C");
set.add("JavaScript");
System.out.println("HashSet after adding elements: " + set);
}
}
Output:
HashSet after adding elements: [Java, JavaScript, Python, C]
addAll() Method
The addAll
method adds all elements from the specified collection to the set.
Syntax
public boolean addAll(Collection<? extends E> c)
Example
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
public class HashSetAddAllExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
List<String> list = new ArrayList<>();
list.add("C");
list.add("JavaScript");
set.addAll(list);
System.out.println("HashSet after addAll: " + set);
}
}
Output:
HashSet after addAll: [Java, JavaScript, Python, C]
clear() Method
The clear
method removes all elements from the set.
Syntax
public void clear()
Example
import java.util.HashSet;
public class HashSetClearExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
set.clear();
System.out.println("HashSet after clear: " + set);
}
}
Output:
HashSet after clear: []
clone() Method
The clone
method returns a shallow copy of the HashSet
instance.
Syntax
public Object clone()
Example
import java.util.HashSet;
public class HashSetCloneExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
HashSet<String> clonedSet = (HashSet<String>) set.clone();
System.out.println("Original HashSet: " + set);
System.out.println("Cloned HashSet: " + clonedSet);
}
}
Output:
Original HashSet: [Java, Python]
Cloned HashSet: [Java, Python]
contains() Method
The contains
method checks if the set contains the specified element.
Syntax
public boolean contains(Object o)
Example
import java.util.HashSet;
public class HashSetContainsExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
boolean containsJava = set.contains("Java");
boolean containsC = set.contains("C");
System.out.println("Contains 'Java': " + containsJava);
System.out.println("Contains 'C': " + containsC);
}
}
Output:
Contains 'Java': true
Contains 'C': false
containsAll() Method
The containsAll
method checks if the set contains all elements from the specified collection.
Syntax
public boolean containsAll(Collection<?> c)
Example
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
public class HashSetContainsAllExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
List<String> list = new ArrayList<>();
list.add("Java");
list.add("C");
boolean containsAll = set.containsAll(list);
System.out.println("Contains all elements of the list: " + containsAll);
}
}
Output:
Contains all elements of the list: false
isEmpty() Method
The isEmpty
method checks if the set is empty.
Syntax
public boolean isEmpty()
Example
import java.util.HashSet;
public class HashSetIsEmptyExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
boolean isEmpty = set.isEmpty();
System.out.println("Is HashSet empty: " + isEmpty);
set.add("Java");
isEmpty = set.isEmpty();
System.out.println("Is HashSet empty after adding element: " + isEmpty);
}
}
Output:
Is HashSet empty: true
Is HashSet empty after adding element: false
iterator() Method
The iterator
method returns an iterator over the elements in the set.
Syntax
public Iterator<E> iterator()
Example
import java.util.HashSet;
import java.util.Iterator;
public class HashSetIteratorExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
set.add("C");
Iterator<String> iterator = set.iterator();
System.out.println("Elements in HashSet using iterator:");
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
Output:
Elements in HashSet using iterator:
Java
C
Python
remove() Method
The remove
method removes the specified element from the set if it is present.
Syntax
public boolean remove(Object o)
Example
import java.util.HashSet;
public class HashSetRemoveExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
boolean removed = set.remove("Python");
System.out.println("Was 'Python' removed? " + removed);
System.out.println("HashSet after removal: " + set);
}
}
Output:
Was 'Python' removed? true
HashSet after removal: [Java]
removeAll() Method
The removeAll
method removes from the set all of its elements that are contained in the specified collection.
Syntax
public boolean removeAll(Collection<?> c)
Example
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
public class HashSetRemoveAllExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
set.add("C");
List<String> list = new ArrayList<>();
list.add("Python");
list.add("C");
boolean removed = set.removeAll(list);
System.out.println("Were elements removed? " + removed);
System.out.println("HashSet after removeAll: " + set);
}
}
Output:
Were elements removed? true
HashSet after removeAll: [Java]
retainAll() Method
The retainAll
method retains only the elements in the set that are contained in the specified collection.
Syntax
public boolean retainAll(Collection<?> c)
Example
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
public class HashSetRetainAllExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
set.add("C");
List<String> list = new ArrayList<>();
list.add("Python");
list.add("C");
boolean changed = set.retainAll(list);
System.out.println("Did the set change? " + changed);
System.out.println("HashSet after retainAll: " + set);
}
}
Output:
Did the set change? true
HashSet after retainAll: [C, Python]
size() Method
The size
method returns the number of elements in the set.
Syntax
public int size()
Example
import java.util.HashSet;
public class HashSetSizeExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
int size = set.size();
System.out.println("Size of HashSet: " + size);
}
}
Output:
Size of HashSet: 2
toArray() Method
The toArray
method returns an array containing all of the elements in the set.
Syntax
public Object[] toArray()
public <T> T[] toArray(T[] a)
Example
import java.util.HashSet;
import java.util.Arrays;
public class HashSetToArrayExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
// Using toArray()
Object[] array = set.toArray();
System.out.println("Array using toArray(): " + Arrays.toString(array));
// Using toArray(T[] a)
String[] stringArray = set.toArray(new String[0]);
System.out.println("Array using toArray(T[] a): " + Arrays.toString(stringArray));
}
}
Output:
Array using toArray(): [Java, Python]
Array using toArray(T[] a): [Java, Python]
spliterator() Method
The spliterator
method returns a Spliterator
over the elements in the set.
Syntax
public Spliterator<E> spliterator()
Example
import java.util.HashSet;
import java.util.Spliterator;
public class HashSetSpliteratorExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
Spliterator<String> spliterator = set.spliterator();
System.out.println("Elements in the Spliterator:");
spliterator.forEachRemaining(System.out::println);
}
}
Output:
Elements in the Spliterator:
Java
Python
stream() Method
The stream
method returns a sequential Stream
with the elements in the set as its source.
Syntax
public Stream<E> stream()
Example
import java.util.HashSet;
import java.util.stream.Stream;
public class HashSetStreamExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
Stream<String> stream = set.stream();
System.out.println("Elements in the Stream:");
stream.forEach(System.out::println);
}
}
Output:
Elements in the Stream:
Java
Python
parallelStream() Method
The parallelStream
method returns a parallel Stream
with the elements in the set as its source.
Syntax
public Stream<E> parallelStream()
Example
import java.util.HashSet;
public class HashSetParallelStreamExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
set.add("C");
set.parallelStream()
.filter(lang -> lang.startsWith("J"))
.forEach(lang -> System.out.println(Thread.currentThread().getName() + " processed: " + lang));
}
}
Output:
ForkJoinPool.commonPool-worker-1 processed: Java
removeIf() Method
The removeIf
method removes all elements of the set that satisfy the given predicate.
Syntax
public boolean removeIf(Predicate<? super E> filter)
Example
import java.util.HashSet;
public class HashSetRemoveIfExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
set.add("C");
boolean removed = set.removeIf(lang -> lang.startsWith("J"));
System.out.println("Were any elements removed? " + removed);
System.out.println("HashSet after removeIf: " + set);
}
}
Output:
Were any elements removed? true
HashSet after removeIf: [C, Python]
forEach() Method
The forEach
method performs the given action for each element of the set until all elements have been processed or the action throws an exception.
Syntax
public void forEach(Consumer<? super E> action)
Example
import java.util.HashSet;
public class HashSetForEachExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
set.add("C");
System.out.println("Elements in the HashSet:");
set.forEach(System.out::println);
}
}
Output:
Elements in the HashSet:
Java
C
Python
Conclusion
The HashSet
class in Java provides a variety of methods to manipulate sets of elements efficiently. This tutorial covered all the methods with examples to help you understand how to use them effectively in your Java applications. By leveraging these methods, you can perform a wide range of operations on sets, such as adding, removing, and iterating over elements, as well as performing actions using streams and predicates.