In this guide, we’re going to take a look at the HashSet class from Java Collections Framework.
We will learn all the APIs that HashSet implementation offers.
HashSet class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.
HashSet implementation is not synchronized - If multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally.
Example:
Set s = Collections.synchronizedSet(new HashSet(...));
This guide covers important HashSet implementation API with examples. All the APIs are referred from HashSet JavaDoc.
1. Set Interface Overview
- The Set interface contains only methods inherited from the Collection interface and adds the restriction that duplicate elements are prohibited.
- A Set that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element.
- As implied by its name, this interface models the mathematical set abstraction.
- Set does not guarantee an insertion order.
2. HashSet class Overview
Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements the Set interface.
The important points about the Java HashSet class are:
- HashSet stores the elements by using a mechanism called hashing.
- HashSet contains unique elements only.
3. Create a HashSet and Add new Elements
add()
The example below shows how to create a HashSet using the HashSet() constructor, and add new elements to it using the add() method.
// Creating a HashSet
Set<String> daysOfWeek = new HashSet<>();
// Adding new elements to the HashSet
daysOfWeek.add("Monday");
daysOfWeek.add("Tuesday");
daysOfWeek.add("Wednesday");
daysOfWeek.add("Thursday");
daysOfWeek.add("Friday");
daysOfWeek.add("Saturday");
daysOfWeek.add("Sunday");
// Adding duplicate elements will be ignored
daysOfWeek.add("Monday");
System.out.println(daysOfWeek);
addAll()
Creating HashSet from Collection Example
List<Integer> list = new ArrayList<>();
list.add(5);
list.add(10);
list.add(15);
list.add(20);
list.add(25);
List<Integer> list2 = new ArrayList<>();
list2.add(3);
list2.add(6);
list2.add(9);
list2.add(12);
list2.add(15);
// Creating a HashSet from another collection (ArrayList)
Set<Integer> set = new HashSet<>(list);
// Adding all the elements from an existing collection to a HashSet
set.addAll(list2);
System.out.println(set);
4. HashSet remove APIs with Example
remove(Object o)
Remove an element from a HashSet (The remove() method returns false if the element does not exist in the HashSet)
Set<Integer> numbers = new HashSet<>();
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
numbers.add(6);
numbers.add(7);
numbers.add(8);
numbers.add(9);
numbers.add(10);
System.out.println("numbers : " + numbers);
boolean isRemoved = numbers.remove(10);
System.out.println("After remove(10) => " + numbers);
removeAll(Collection<?> c)
Remove all elements belonging to a given collection from a HashSet
Set<Integer> numbers = new LinkedHashSet<>();
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
numbers.add(6);
numbers.add(7);
numbers.add(8);
numbers.add(9);
numbers.add(10);
List<Integer> perfectSquares = new ArrayList<>();
perfectSquares.add(4);
perfectSquares.add(9);
numbers.removeAll(perfectSquares);
System.out.println("After removeAll(perfectSquares) => " + numbers);
removeIf(Predicate<? super Integer> filter)
Remove all elements matching a given predicate
numbers.removeIf(num -> num % 2 == 0);
System.out.println("After removeIf() => " + numbers);
clear()
Remove all elements from HashSet (clear it completely)
numbers.clear();
System.out.println("After clear() => " + numbers);
5. Demonstration of How the Set contains duplicates and null values?
public class SetInterfaceHashImpl {
public static void main(String[] args) {
nullValueDemo();
duplicateValueDemo();
//bulkOperationDemo();
}
// Set can contain one null value
private static void nullValueDemo() {
Set < String > set = new HashSet < > ();
set.add(null);
set.add(null);
System.out.println(set.toString());
}
// it is not contain duplicate elements
private static void duplicateValueDemo() {
Set < String > set = new HashSet < > ();
set.add("element1");
set.add("element1");
// displays only one element
System.out.println(set.toString());
}
}
Output :
[null]
[element1]
6. HashSet Bulk Operations APIs with Examples
Let's write below bulk operation methods with examples
- addAll()
- retainAll()
- containsAll()
- removeAll()
// Set bulk operations
private static void bulkOperationDemo() {
Set < String > set = new HashSet < > ();
set.add("element1");
set.add("element2");
set.add("element3");
set.add("element4");
// Appends all of the elements in the specified collection to the end of
// this list,
// in the order that they are returned by the specified collection's
// iterator (optional operation).
Set < String > union = new HashSet < String > ();
union.addAll(set);
printMessage(union, "addALL operation example ");
// Retains only the elements in this list that are contained in
// the specified collection (optional operation).
Set < String > intersection = new HashSet < String > ();
intersection.add("element 1");
intersection.add("element 2");
intersection.add("element 3");
intersection.add("element 4");
System.out.println("retainAll -- > " + intersection.retainAll(set));
// Removes from this list all of its elements that are
// contained in the specified collection (optional operation).
Set < String > difference = new HashSet < String > ();
difference.add("element 1");
difference.add("element 2");
difference.add("element 3");
difference.add("element 4");
System.out.println("removeAll operation example ---> " + difference.removeAll(set));
printMessage(difference, "removeAll operation example ");
Set < String > checking = new HashSet < String > ();
checking.add("element 1");
checking.add("element 2");
checking.add("element 3");
checking.add("element 4");
System.out.println("containsAll operation example ---- > " + checking.containsAll(set));
}
private static void printMessage(Set < String > difference, String msg) {
difference.forEach(key - > System.out.println(msg + key));
}
7. Iterating over a HashSet
The following example shows different ways of iterating over a HashSet
- Iterate over a HashSet using Java 8 forEach and lambda expression.
- Iterate over a HashSet using iterator().
- Iterate over a HashSet using iterator() and Java 8 forEachRemaining() method.
- Iterate over a HashSet using a simple for-each loop.
iterator()
Set<String> list = new HashSet<>();
list.add("element 1");
list.add("element 2");
list.add("element 3");
list.add("element 4");
// using Iterator
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String str = iterator.next();
System.out.println(" only forward direction ---" + str);
}
Advance for() loop
// Using advanced for loop
for (String str : list) {
System.out.println(" only forward direction ---" + str);
}
forEachRemaining()
// Java 8
list.forEachRemaining(str -> System.out.println(" only forward direction ---" + str));
forEach()
// Java 8
list.forEach(str -> System.out.println(" only forward direction ---" + str));
8. HashSet with User-defined objects
This example shows how to create a HashSet of user-defined objects.
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
class Customer {
private long id;
private String name;
public Customer(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// Two customers are equal if their IDs are equal
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Customer customer = (Customer) o;
return id == customer.id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Customer{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
public class HashSetUserDefinedObjectExample {
public static void main(String[] args) {
Set<Customer> customers = new HashSet<>();
customers.add(new Customer(101, "Rajeev"));
customers.add(new Customer(102, "Sachin"));
customers.add(new Customer(103, "Chris"));
/*
HashSet will use the `equals()` & `hashCode()` implementations
of the Customer class to check for duplicates and ignore them
*/
customers.add(new Customer(101, "Rajeev"));
System.out.println(customers);
}
}
Output
[Customer{id=101, name='Rajeev'}, Customer{id=102, name='Sachin'}, Customer{id=103, name='Chris'}]
9. How to make HashSet thread-safe?
This class implementation is not synchronized so it is not thread-safe. If multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally.HashSet must be synchronized externally.
Example :
Example :
// HashSet is not synchronized
private static void synchronizedHashSetDemo() {
Set<String> set = new HashSet<>();
Set<String> synchronizedSet = Collections.synchronizedSet(set);
}
Related Collections Framework API Guides
- Collections Framework - ArrayList Class
- Collections Framework - LinkedList Class
- Collections Framework - CopyOnWriteArrayList
- Collections Framework - HashSet Class
- Collections Framework - LinkedHashSet Class
- Collections Framework - TreeSet Class
- Collections Framework - CopyOnWriteArraySet
- Collections Framework - EnumSet
- Collections Framework - HashMap Class
- Collections Framework - LinkedHashMap Class
- Collections Framework - TreeMap class
- Collections Framework - EnumMap
- Collections Framework - WeakHashMap
- Collections Framework - IdentityHashMap
References
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course