Java HashSet Example

In this article, we will discuss important Java HashSet Class methods with examples.
Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements Set interface.
The important points about Java HashSet class are:
  • HashSet stores the elements by using a mechanism called hashing.
  • HashSet contains unique elements only.
  • Difference between List and Set
  • List can contain duplicate elements whereas Set contains unique elements only.

Create a HashSet and Adding new Elements Example

add() method example

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() method example

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);

HashSet remove API's with Example

remove(Object o) method example

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) method example

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) method example

Remove all elements matching a given predicate
numbers.removeIf(num -> num % 2 == 0);
System.out.println("After removeIf() => " + numbers);

clear() method example

Remove all elements from HashSet (clear it completely)
numbers.clear();
System.out.println("After clear() => " + numbers);

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]

HashSet Bulk Operations API's 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));
}

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() method example

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() method example

// Java 8
list.forEachRemaining(str -> System.out.println(" only forward direction ---" + str));

forEach() method example

// Java 8
list.forEach(str -> System.out.println(" only forward direction ---" + str));

HashSet with User-defined objects Example

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'}]

Related Collections Examples

Comments