In this article we will dive into Java HashSet and it’s most commonly used methods with various examples. Java HashSet is one of the most commonly used implementation of Set collection interface.
Java
HashSet
is a hash table data structure implementation of the Set interface,HashSet
stores its element by a process called hashing, internally it uses aHashMap
implementation to store elements.
1. Java HashSet features
- This class implements the Set interface, the under lying data structure is hash table (actually a HashMap instance).
- Insertion order is not preserved and the order is based on hash code of the objects.
- Duplicate objects are not allowed.
- If we are trying to insert duplicate objects we won’t get compile time error and run-time error, add() method simply returns false, and false means new element not inserted in to set, the old element remains same.
- null insertion is possible.
- A Java HashSet is non synchronized, means HashSet operations are not thread safe.
2. Class hierarchy of HashSet
Following image illustrates the hierarchy of Java HashSet class.
3. Create HashSet instance
Following are the constructors in Java HashSet to create instances.
3.1. Constructors in java HashSet :
HashSet()
: creates default initial capacity is 16 and default load factor is 0.75.HashSet(int initialCapacity)
: creates a new, empty set has the specified initial capacity and default load factor 0.75.HashSet(int initialCapacity, float loadFactor)
: creates a new, empty set has the specified initial capacity and the specified load factor.HashSet(Collection C)
: creates a new set containing the elements in the specified collection, this is useful to convert other Set implementations to HashSet.
//Instantiating HashSet with default constructor Set<String> hashset = new HashSet<>();
The above code constructs a new, empty set, the backing HashMap instance, means a new HashMap creates internally when construct a new HashSet instance and it uses hashmap implementation to store elements.
//java.util.HashSet default constructor implementation public HashSet() { map = new HashMap<>(); }
4. Java HashSet methods and examples
Let’s have a look into most commonly used HashSet methods with simple examples.
4.1. Add objects to HashSet
add()
method adds the specified element to this set if it is not already present. If an element was added, the method returns true, otherwise false.
public class HashAddDemo { public static void main(String[] args) { //Instantiating HashSet with default constructor Set<String> hashset = new HashSet<>(); //add() hashset.add("Peter"); // returns true System.out.println(hashset); // Prints [Peter] hashset.add("Gerhard"); // returns true System.out.println(hashset); // Prints [Gerhard, Peter] //adding duplicate System.out.println(hashset.add("Gerhard")); // returns false; } }
Output :
[Peter] [Gerhard, Peter] false
4.2. Verify HashSet empty and size
isEmpty()
method returns true if this set contains no elements, otherwise false. We can use this method to know whether the set has any elements or not.
size()
method returns the number of elements in this set (its cardinality).
public class HashAddDemo { public static void main(String[] args) { //Instantiating HashSet with default constructor Set<String> hashset = new HashSet<>(); hashset.add("Peter"); hashset.add("Vijay"); hashset.add("John"); hashset.add("Mike"); System.out.println(hashset.size()); // 4 System.out.println(hashset.isEmpty()); // false } }
Output :
4 false
4.3. Verify HashSet contains value
contains()
method returns true
if this set contains the specified element. We can use this method to know whether specific element already exist in Set or not.
public class HashSetContainsDemo { public static void main(String[] args) { Set<String> hashset1 = new HashSet<>(); hashset1.add("Peter"); hashset1.add("Vijay"); hashset1.add("John"); hashset1.add("Mike"); System.out.println(hashset1.contains("John")); // ture System.out.println(hashset1.contains("Arthur")); // false Set<String> hashset2 = new HashSet<>(); hashset2.add("John"); hashset2.add("Mike"); System.out.println(hashset1.containsAll(hashset1)); // true } }
Output :
true false true
4.4. Remove and clear values in HashSet
remove()
method removes the specified element from this set if it is present and return true. We can use this method to remove specific element form Set.
clear()
method removes all of the elements from this set. We can use this method to empty the current set.
public class HashSetContainsDemo { public static void main(String[] args) { Set<String> hashset1 = new HashSet<>(); hashset1.add("Peter"); hashset1.add("Vijay"); hashset1.add("John"); hashset1.add("Mike"); System.out.println(hashset1.remove("John")); // ture System.out.println(hashset1); // [Vijay, Mike, Peter] Set<String> hashset2 = new HashSet<>(); hashset2.add("John"); hashset2.add("Mike"); System.out.println(hashset1.removeAll(hashset2)); // true System.out.println(hashset1); // [Vijay, Peter] hashset1.clear(); System.out.println(hashset1); // [] } }
Output :
true [Vijay, Mike, Peter] true [Vijay, Peter] []
4.5. Iterate or loop HashSet
iterator()
returns an iterator over the elements in this set. The elements are returned in no particular order. We can use this method to iterate each element from the java HashSet.
Following example demonstrates iterate HashSet
in different approches.
public class IterateHashSetDemo { public static void main(String[] args) { Set<String> hashset = new HashSet<>(); hashset.add("Peter"); hashset.add("Vijay"); hashset.add("John"); hashset.add("Mike"); System.out.println("---- Iterate using Iterator ----"); Iterator<String> iterator = hashset.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } System.out.println("---- Iterate using for-each loop ----"); for(String s : hashset) System.out.println(s); System.out.println("---- Iterate using forEach method ----"); hashset.forEach(s -> System.out.println(s)); // this is useful if you already have stream instance System.out.println("---- Iterate using Stream forEach method ----"); hashset.stream().forEach(s -> System.out.println(s)); } }
Output :
---- Iterate using Iterator ---- Vijay Mike John Peter ---- Iterate using for-each loop ---- Vijay Mike John Peter ---- Iterate using forEach method ---- Vijay Mike John Peter ---- Iterate using Stream forEach method ---- Vijay Mike John Peter
4.6. Filter HashSet values
Since java 8 we can apply Stream to any collection object and then apply filter.
public class FilterHashSetDemo { public static void main(String[] args) { Set<String> hashset = new HashSet<>(); hashset.add("Peter"); hashset.add("Vijay"); hashset.add("John"); hashset.add("Mike"); hashset.add("Martin"); // get names start with "M" hashset.stream().filter(s -> s.startsWith("M")) .forEach(s -> System.out.println(s)); } }
Output :
Mike Martin