Remove duplicates from an array in Java

In this section, we will write a Java program to remove duplicate integer elements in an Array.



Method 1: Remove duplicates using temp Array

To remove the duplicate element from an array, the array must be in sorted order. If an array is not sorted, you can sort it by calling Arrays.sort(array) method.
import java.util.Arrays;

public class Main {

private static void removeDuplicates(int[] a) {

Arrays.sort(a);
int[] temp = new int[a.length];

int j = 0;
for (int i = 0; i < a.length - 1; i++) {
if (a[i] != a[i + 1]) {
temp[j++] = a[i];
}
}
temp[j++] = a[a.length - 1];

for (int i = 0; i < j; i++) {
a[i] = temp[i];
}

for (int i = 0; i < j; i++) {
System.out.println(temp[i]);
}
}

public static void main(String []args)
{
int[] a = { 6, 1, 1, 2, 3, 4, 5, 5, 1, 2 };
removeDuplicates(a);

}
}

Console Output:
1
2
3
4
5
6



Method 2: Remove duplicates using HashSet

HashSet provided add() method to remove duplicates from an array. The add() method returns true if this set did not already contain the specified element.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class Main {

private static void removeDuplicates( Integer[] a){
Arrays.sort(a);
Set<Integer> set = new HashSet<Integer>();

Integer[] temp = new Integer[a.length];
int j = 0;
for (final Integer element : a) {
if(set.add(element)){
temp[j++] = element;
}
}

// display temp array
for (int i = 0; i < j; i++) {
System.out.println(temp[i]);
}
}

public static void main(String []args)
{
Integer[] a = {6,1,1,2,3,4,4,5};
removeDuplicates(a);

}
}


Console Output:
1
2
3
4
5
6

More related topics,

Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example