Java HashSet

If you don't want to allow duplicate elements or items in your resizable array then you should use HashSet. Java HashSet class implements the Set interface that doesn't allow duplicate elements as it's members or elements.

The following are the important methods that can be used in HashSet or Set interface.



MethodsReturn typesDescription
add(E element)booleanAppends the specified element to the end of this list.
add(int index, E element)voidInserts the specified element at the specified position in this list.
addAll(Collection c)booleanAppends 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.
addAll(int index, Collection c)booleanAppends 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.
get(int index)E (element type)Returns the element at the specified position in this list.
isEmpty()booleanReturns true if this list contains no elements.
iterator()Iterator(E)Returns an iterator over the elements in this list in proper sequence.
remove(int index)ERemoves the element at the specified position in this list.
removeAll(Collection c)booleanRemoves from this list all of its elements that are contained in the specified collection.
removeIf(Predicate filter)booleanRemoves all of the elements of this collection that satisfy the given predicate.
set(int index, E element)EReplaces the element at the specified position in this list with the specified element.
size()intReturns the number of elements in this list.
trimToSize()voidTrims the capacity of this ArrayList instance to be the list's current size.
toArray()ObjectReturns an array containing all of the elements in this list in proper sequence (from first to last element).
contains()booleanReturns true if this list contains the specified element
clone()ObjectReturns a shallow copy of this ArrayList instance. (The elements themselves are not copied.)
equals()booleanChecks two lists are equal or not (returns true ir false)
indexOf()intReturns the index of the first occurrence of the specified element in this list.
indexOf()intReturns the index of the last occurrence of the specified element in this list.
sort()voidSorts the list alphabetically or numerically in a specified order (Eescending or Descending)
stream()StreamReturns a sequential Stream with this collection as its source.

# Creating empty HashSet instance


// Syntax: (T stands for Type)
HashSet set = new HashSet();

//creating empty HashSet
HashSet set = new HashSet();

# Adding elements to HashSet

# Add new elements or items using add() method.


import java.util.HashSet;

public class Main{
  public static void main (String[] args){
    HashSet fruits = new HashSet();
    //add elements using add method
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Cherry");
    fruits.add("Guava");
    fruits.add("Plum");
    
    //print the elements
    System.out.println(fruits);
  }
}

If you run the above example application you see the following output in the console:


[Guava, Apple, Plum, Cherry, Banana] 

Note: HashSet or Set interface doesn't maintain the insertion order.

# Numbers as elements in HashSet (Integer)


import java.util.HashSet;

public class Main{
  public static void main (String[] args){
    HashSet numbers = new HashSet();
    //add elements using add method
    numbers.add(1);
    numbers.add(2);
    numbers.add(3);
    numbers.add(4);
    numbers.add(5);
    
    //print the elements
    System.out.println(numbers);
  }
}

/**
 * Output:
 * [1, 2, 3, 4, 5]
 */

Note: Numbers always maintain the ordinal order (1, 2, 3,..)

Like:


import java.util.HashSet;

public class Main{
  public static void main (String[] args){
    HashSet numbers = new HashSet();
    //add elements using add method
    numbers.add(1);
    numbers.add(2);
    numbers.add(30);
    numbers.add(4);
    numbers.add(5);
    
    //print the elements
    System.out.println(numbers);
  }
}

/**
 * Output:
 * [1, 2, 4, 5, 30]
 */

# Duplicate elements will be ignored

We have already learned that Set or HashSet doesn't allow duplicate members as it's items. Thus, it ignore the duplicate members.


import java.util.HashSet;

public class Main{
  public static void main (String[] args){
    HashSet fruits = new HashSet();
    //add elements using add method
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Apple");
    fruits.add("Guava");
    fruits.add("Plum");
    fruits.add("Banana")
    
    //print the elements
    System.out.println(fruits);
  }
}

/**
 * Output: 
 * [Guava, Apple, Plum, Banana]
 */

You see duplicate members are ignored in HashSet. So, Only use Set or HashSet in your application when maintaining insertion order is not the priority and there will be no duplicate members.

# Iterate the HashSet elements using for loop


import java.util.ArrayList;

public class Main{
  public static void main (String[] args){
    HashSet fruits = new HashSet();
    //add elements using add method
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Cherry");
    fruits.add("Guava");
    fruits.add("Plum");
    
    //iterate and print 
    for(int i = 0; i <=fruits.size(); i++){
      System.out.println(fruits.get(i));
    }
  }
}

If you run the above example you get the following output:


Cherry 
Banana
Apple 
Plum
Guava

# Iterating ArrayList elements using for each loop.


import java.util.ArrayList;

public class Main{
  public static void main (String[] args){
    HashSet fruits = new HashSet();
    //add elements using add method
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Cherry");
    fruits.add("Guava");
    fruits.add("Plum");
    
    //iterating ArrayList elements
    for(String f: fruits){
      System.out.println(f);
    }
  }
}
/**
 * //Output 
 * Guava 
 * Plum
 * Cherry 
 * Banana
 * Apple
 */

# Iterating ArrayList using Iterator


import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
 //Or import all the classes 
 //import java.util.*;
 
 public class Main{
   public static void main (String[] args) {
     //Creating ArrayList
     HashSet fruits = new HashSet();
     //add new elements 
     fruits.add("Apple");
     fruits.add("Banana");
     fruits.add("Cherry");
     fruits.add("Guava");
     fruits.add("Plum");
     
     //iterate using Iterator
     Iterator list = fruits.iterator(); //getting Iterator
     while(list.hasNext()){ //check if any elements exists or not
       System.out.println(list.next()); //printing the elements 
     }
   }
 }
 
/**
 * Banana 
 * Guava
 * Plum
 * Apple
 * Cherry 
 */

# Remove an element from ArrayList

To remove an element, use the remove(int index). Don't forget to specified the index number.

Like:


import java.util.ArrayList;

public class Main{
  public static void main (String[] args){
    ArrayList fruits = new ArrayList();
    //add elements using add method
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Cherry");
    fruits.add("Guava");
    fruits.add("Plum");
 
    //iterate ArrayList 
    System.out.println("Before Removing elements");
    for(String f: fruits){
      System.out.println(f);
    }
    
    //
    System.out.println("After removing the first element");
    
    fruits.remove(0);
    //iterate now 
    for(String f: fruits){
      System.out.println(f);
    }
  }
}


//output
Before Removing elements
Apple
Banana
Cherry
Guava
Plum
After removing the first element
Banana
Cherry
Guava
Plum

Note: It is possible to use remove(element) to remove a particular element based on their name instead of position.

# Sort HashSet elements

It is not possible to sort HashSet or Set interface items. Because, HashSet is unordered collection. It means, the items of HashSet don't maintain the insertion order. Thus you can not sort the HashSet items. But, it is required to sort the HashSet then you can convert the Set to List and then sort.

The following error you will get if you try to sort the below example:


import java.util.HashSet;
import java.util.Collections;

public class Main{
  public static void main (String[] args){
    HashSet fruits = new HashSet();
    //add new elements 
    fruits.add("Plum");
    fruits.add("Cherry");
    fruits.add("Banana");
    fruits.add("Apple");
    fruits.add("Guava");
    
    //sort fruits and then iterate 
    Collections.sort(fruits);
    
    //iterating HashSet elements 
    for(String f: fruits){
      System.out.println(f);
    }
  }
}

Error Message...


// output: (error message)

Main.java:16: error: no suitable method found for sort(HashSet)
    Collections.sort(fruits);
               ^
    method Collections.sort(List) is not applicable
      (cannot infer type-variable(s) T#1
        (argument mismatch; HashSet cannot be converted to List))
    method....