Java – How To Remove Duplicate Values in Array

This post shows you how to remove duplicate values in a Java array by using HashSet class, which contains unique values only.

 

Let’s consider the following code:

DuplicatesRemovingExample.java
package com.bytenota;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class DuplicatesRemovingExample {
    
    public static void main(String[] args) {
        int[] intArray = { 1, 2, 2, 1, 3, 4, 4 };
        
        System.out.println("Original array: " + Arrays.toString(intArray));
        
        // create a HashSet object to contain unique values
        Set<Integer> result = new HashSet<Integer>();
        for (int i = 0; i < intArray.length; i++) {
            result.add(intArray[i]);
        }
        
        System.out.println("Result array: " + result.toString());
    }
    
}

In the above code, we create a HashSet object to contain the unique values in the Integer array (i.e. intArray),  then iterate through the intArray and add its values to the HashSet object.

 

Here is the output:

Original array: [1, 2, 2, 1, 3, 4, 4]
Result array: [1, 2, 3, 4]

0 0 vote
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x