Java HashSet is an unordered and no-duplicate elements collection, implementation of java.util.Set interface. HashSet has the following attributes

  • Backed by hash table data structure (actually a HashMap instance)

  • No guarantees to the iteration order

  • Contains no duplicate elements, at most one null element

  • Offers constant time performance for add, remove, contains and size operations, assuming the hash function distributes the elements properly among the buckets

  • Unsynchronized implementation. In multi-threading environment with at least one thread modifies the list, it must be synchronized externally

HashSet declaration and initialization

  • In one line with Arrays.asList
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3));  
  • Create an unmodifiable set in one line with Set.of since Java 9+
Set<Integer> set = Set.of(1, 2, 3);  
  • In one line with double brace initialization (should not be used)
Set<Integer> set = new HashSet<Integer>(){{  
    add(1);
    add(2);
    add(3);
}};

Double brace initialization can lead to memory leaks as it creates an anonymous class with a reference to the owner object

  • In multiple lines
Set<Integer> set = new HashSet<>();  
set.add(1);  
set.add(2);  
set.add(3);  

HashSet traversal

  • with for-each loop aka enhanced for-loop thanks to Iterable implementation
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3));  
for(int ele : set) {  
    System.out.println(ele);
}
  • with forEach(Consumer<? super T> action) of Iterable interface, since Java 8+
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3));  
set.forEach(System.out::println);  
  • with Iterator<E> iterator() returns an iterator over the set elements in no particular order
Iterator iter = set.iterator();  
while (iter.hasNext())  
    System.out.println(iter.next());

Query operations

  • int size() gets the number of elements in a set, O(1)
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3));  
set.size(); // 3
  • boolean isEmpty() checks if a set contains no elements, O(1)
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3));  
set.isEmpty(); // false
  • boolean contains(Object o) checks if a set contains the specified element, O(1)
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3));  
set.contains(1); // true  
set.contains("a"); // false  
  • boolean containsAll(Collection<?> c) checks if a set contains all elements of the specified collection
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3));  
System.out.println(set.containsAll(Arrays.asList(1, 3))); // true  
System.out.println(set.containsAll(Arrays.asList(1, 3, 1))); // true  
System.out.println(set.containsAll(Arrays.asList(4))); // false
  • Iterator<E> iterator() gets an iterator over the set elements in no particular oder
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3));  
Iterator iter = set.iterator();  
  • <T> T[] toArray(T[] a) gets an array containing all elements in a set with the runtime type T as the specified array. A new array is allocated if the set size greater than the array a size
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3));  
Integer[] arr = set.toArray(new Integer[0]);  
System.out.println(Arrays.toString(arr)); // [1, 2, 3]

Integer[] arr2 = new Integer[4];  
set.toArray(arr2);  
System.out.println(Arrays.toString(arr2)); // [1, 2, 3, null]

Modification operations

  • boolean add(E e) adds an element to the set, O(1)
Set<Integer> set = new HashSet<>();  
set.add(1); // the set now is [1]
  • boolean remove(Object o) removes element from a set, O(1)
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3));  
set.remove(2); // the set now is [1, 3]
  • boolean retainAll(Collection<?> c) retains all elements from a set that are contained in the specified collection
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3));  
set.retainAll(Arrays.asList(1, 4)); // the set now is [1]
  • boolean removeAll(Collection<?> c) removes all elements from a set that are contained in the specified collection
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3));  
set.removeAll(Arrays.asList(1, 4)); // the set now is [2, 3]
  • boolean removeIf(Predicate<? super E> filter) removes all elements from a set that satisfy the given predicate filter
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3));  
set.removeIf(x -> x >= 2); // the set now is [1]
  • void clear() removes all elements from a set
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3));  
set.clear(); // the set now is empty []