HashSet in java with Example

HashSet in java with Example

Java HashSet internally uses hash-table data structure.

In Java HashSet Duplicates are not allowed.

If you are trying to insert duplicates , you won’t get any compile time or run time errors. add() method simply returns false.

In HashSet class Insertion order is not preserved and all objects will be inserted based on Hash-code of object.

java Hashset permits to insert Different types of object.

‘null’ insertion is possible.

HashSet Implements Serializable and Clonable interface but not RandomAccess.

HashSet is the best choice ,if our frequent operation is search operation.

HashSet is not thread-safe. If multiple threads try to modify a HashSet at the same time, then the final outcome is not-deterministic. You must explicitly synchronize concurrent access to a HashSet in a multi-threaded environment.


Creating HashSet or Constructor of HashSet

Following are four constructors are available in HashSet.

HashSet h= new HashSet();

-create an empty HashSet object with default initial capacity 16 & default Fill retio 0.75.

HashSet hs =new HashSet(int initialCapacity);

-creates an empty HashSet object with specified initial capacity & default Fill retio 0.75.

HashSet hs=new HashSet(int initialCapacity, float loadFactor);

Creates an empty HashSet object with specified initial capacity & specified load factor (or Fill Ratio)

HashSet h= new HashSet(Collection c)

Creating a HashSet from another collection

Load Factor/Fill Ratio:

After loading the how much factor , a new HashSet Object will be created , that factor is called as Load Factor or Fill Ratio.

HashSet in java with Example

import java.util.*;
 public class HashSetDemo
 {
   public static void main(String[] args)
   {
    // creating HashSet
     HashSet hs=new HashSet();
     //Adding Elements into HashSet using add method
     hs.add("Ajay");
     hs.add("Baban");
     hs.add("Ram");
     hs.add("Suresh");
     hs.add("Raj");
     System.out.println("Elements in HashSet "+hs);
     //when you trying to add duplicates elements into HashSet object is not inseted but it will return false
     System.out.println(hs.add("Ajay"));
     System.out.println("After adding Elements into hashSet"+hs);
 }
 }
   

Output:

Elements in HashSet [null, Suresh, Raj, Ajay, Baban, Ram]
false
After adding Elements into hashSet[null, Suresh, Raj, Ajay, Baban, Ram]

Creating a HashSet from another collection

The following example shows how to

  • HashSet(Collection c) :Create a HashSet from another collection using this constructor.
  • addAll() :Add all the elements from a collection to the HashSet using the  addAll() method.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CreateHashSetFromCollectionExample {
    public static void main(String[] args) {
        List<Integer> evenNumber= new ArrayList<>();
        evenNumber.add(2);
        evenNumber.add(4);
        evenNumber.add(10);
        evenNumber.add(20);
        evenNumber.add(24);
        System.out.println(evenNumber);

        List<Integer> oddNumber= new ArrayList<>();
        oddNumber.add(3);
        oddNumber.add(7);
        oddNumber.add(9);
        oddNumber.add(13);
        oddNumber.add(15);
        System.out.println(oddNumber);

        // Creating a HashSet from another collection (ArrayList)
        Set<Integer> allNumbers= new HashSet<>(evenNumber);

        // Adding all the elements from an existing collection to a HashSet
        allNumbers.addAll(oddNumber);

        System.out.println(allNumbers);
    }
}
# Output
[2, 4, 10, 20, 24]
[3, 7, 9, 13, 15]
[2, 3, 4, 20, 7, 24, 9, 10, 13, 15]

HashSet simple operations

  • isEmpty():Check if a HashSet is empty
  •  size() :Find the number of elements in the HashSet
  • contains() :Check if an element exists in the HashSet
import java.util.HashSet;
import java.util.Set;

public class HashSetSimpleOperationsDemo {
    public static void main(String[] args) {
        Set<String> popularCricketer = new HashSet<>();

        // Check if a HashSet is empty
        System.out.println("Is popularCricketers set empty? : " + popularCricketer.isEmpty());

        popularCricketer.add("Sachin");
        popularCricketer.add("Ricky");
        popularCricketer.add("Sourav");
        popularCricketer.add("Virat");
        popularCricketer.add("Ravindra");

        // Find the size of a HashSet
        System.out.println("Number of cricketers in the HashSet " + popularCricketer.size());

        // Check if the HashSet contains an element
        String cricketerName = "Rohit";
        if(popularCricketer.contains(cricketerName)) {
            System.out.println(cricketerName + " is in the popular cricketer set.");
        } else {
            System.out.println(cricketerName + " is not in the popular cricketer set.");
        }
    }
}
# Output
Is popularCricketers set empty? : true
Number of cricketers in the HashSet 5
Rohit is not in the popular cricketer set.

Removing elements from a HashSet

This example shows how to:

  • remove():Remove an element from a HashSet.The remove() method returns false if the element does not exist in the HashSet
  • removeAll():Remove all the elements that exist in a given collection from the HashSet.
  • removeIf(); all the elements that satisfy a given predicate from the HashSet.
  • clear():Clear the HashSet completely by removing all the elements.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class HashSetRemoveDemo {
    public static void main(String[] args) {
        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);

        // Remove an element from a HashSet (The remove() method returns false if the element does not exist in the HashSet)
        boolean isRemoved = numbers.remove(10);
        System.out.println("After remove(10) => " + numbers);
        
        // Remove all elements belonging to a given collection from a HashSet
        List<Integer> perfectCubes = new ArrayList<>();
        perfectCubes.add(8);
        perfectCubes.add(9);

        numbers.removeAll(perfectCubes);
        System.out.println("After removeAll(perfectCubes) => " + numbers);

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

        // Remove all elements from HashSet (clear it completely)
        numbers.clear();
        System.out.println("After clear() => " + numbers);
    }
}
# Output
numbers : [2, 3, 4, 5, 6, 7, 8, 9, 10]
After remove(10) => [2, 3, 4, 5, 6, 7, 8, 9]
After removeAll(perfectCubes) => [2, 3, 4, 5, 6, 7]
After removeIf() => [3, 5, 7]
After clear() => []

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 simple for-each loop.
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class IterateOverHashSetDemo {
    public static void main(String[] args) {
        Set<String> popularCricketers = new HashSet<>();
        popularCricketers.add("Rohit");
        popularCricketers.add("Mayank");
        popularCricketers.add("Cheteshewar");
        popularCricketers.add("Virat");
        popularCricketers.add("Ajinkya");
        popularCricketers.add("Ravindra");

        System.out.println("=== Iterate over a HashSet using Java 8 forEach and lambda ===");
        popularCricketers.forEach(popularCricketer -> {
            System.out.println(popularCricketer);
        });

        System.out.println("=== Iterate over a HashSet using iterator() ===");
        Iterator<String> popularCricketersIterator = popularCricketers.iterator();
        while (popularCricketersIterator.hasNext()) {
            String popularCricketer = popularCricketersIterator.next();
            System.out.println(popularCricketer);
        }

        System.out.println("=== Iterate over a HashSet using iterator() and Java 8 forEachRemaining() method ===");
       popularCricketersIterator = popularCricketers.iterator();
        popularCricketersIterator.forEachRemaining(popularCricketer -> {
            System.out.println(popularCricketer);
        });

        System.out.println("=== Iterate over a HashSet using simple for-each loop ===");
        for(String popularCricketer: popularCricketers) {
            System.out.println(popularCricketer);
        }
    }
}
# Output
=== Iterate over a HashSet using Java 8 forEach and lambda ===
Rohit
Ravindra
Ajinkya
Mayank
Cheteshewar
Virat
=== Iterate over a HashSet using iterator() ===
Rohit
Ravindra
Ajinkya
Mayank
Cheteshewar
Virat
=== Iterate over a HashSet using iterator() and Java 8 forEachRemaining() method ===
Rohit
Ravindra
Ajinkya
Mayank
Cheteshewar
Virat
=== Iterate over a HashSet using simple for-each loop ===
Rohit
Ravindra
Ajinkya
Mayank
Cheteshewar
Virat

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 Emloyee {
    private long id;
    private String name;

    public Emloyee(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;
        Emloyee emloyees = (Emloyee) o;
        return id == emloyees.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<Emloyee> emloyees = new HashSet<>();
        emloyees.add(new Emloyee(101, "Rohit"));
        emloyees.add(new Emloyee(102, "Sachin"));
        emloyees.add(new Emloyee(103, "Chris"));

        /*
          HashSet will use the `equals()` & `hashCode()` implementations 
          of the Customer class to check for duplicates and ignore them
        */
        emloyees.add(new Emloyee(101, "Rohit"));

        System.out.println(emloyees);
    }
}
# Output
[Customer{id=101, name='Rohit'}, Customer{id=102, name='Sachin'}, Customer{id=103, name='Chris'}]

Leave a Reply