Sunday, June 14, 2026
HomeLanguagesJavaGet Unique Values from ArrayList in Java

Get Unique Values from ArrayList in Java

Let’s see how to get unique values from ArrayList. Convert ArrayList to HashSet to insert duplicate values in ArrayList but on the other hand, HashSet is not allowing to insert any duplicate value. While converting ArrayList to HashSet all the duplicate values are removed and as a result, unique values are obtained.

Example:

INPUT : ArrayList = [a, b, c, b, d, a, c]
OUTPUT: Unique = [a, b, c, d]

INPUT : ArrayList = [1, 5, 2, 4, 3, 4, 5]
OUTPUT: Unique = [1, 2, 3, 4, 5]

Approach:

  • Create a ArrarList.
  • Add elements in ArrayList.
  • Create HashSet and pass in HashSet constructor.
  • Print HashSet object.

Below is the implementation of the above approach:

Java




// Get Unique Values from ArrayList in Java
import java.util.ArrayList;
import java.util.HashSet;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // Create ArrayList
        ArrayList<String> ArrList = new ArrayList<String>();
  
        // add values in ArrayList
        ArrList.add("a");
        ArrList.add("b");
        ArrList.add("c");
        ArrList.add("b");
        ArrList.add("d");
        ArrList.add("a");
        ArrList.add("c");
  
        // display original ArrayList
        System.out.println("Original ArrayList is : "
                           + ArrList);
  
        // convert ArrayList to HastSet.
        HashSet<String> hset = new HashSet<String>(ArrList);
  
        // display HastSet
        System.out.println("ArrayList Unique Values is : "
                           + hset);
    }
}


Output

Original ArrayList is : [a, b, c, b, d, a, c]
ArrayList Unique Values is : [a, b, c, d]

Time Complexity: O(n), where n is the length of the original ArrayList.

RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS