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

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java, Spring Boot Mini Project - Library Management System - Download

Java - Blowfish Encryption and decryption Example

Java - DES Encryption and Decryption example

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete

ReactJS - Bootstrap - Buttons

Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

Top 5 Java ORM tools - 2024

Java - How to Count the Number of Occurrences of Substring in a String