Question:
How to remove duplicates from an array in place using Java?

Summary:

The codes below do not use any collection classes to get rid of duplicates. However. the below code will still remove duplicates from an array in place using Java.


Solution:

import java.util.Arrays;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;


/**

 * Java program to remove duplicates from this array. You don't

 * need to physically delete duplicate elements, replacing with null, or

 * empty or default value is ok.

 *

 * @author http://javarevisited.blogspot.com

 */

public class TechnicalInterviewTest {


    private static final Logger logger = LoggerFactory.getLogger(TechnicalInterviewTest.class);


    public static void main(String args[]) {


        int[][] test = new int[][]{

            {1, 1, 2, 2, 3, 4, 5},

            {1, 1, 1, 1, 1, 1, 1},

            {1, 2, 3, 4, 5, 6, 7},

            {1, 2, 1, 1, 1, 1, 1},};


        for (int[] input : test) {

            System.out.println("Array with Duplicates       : " + Arrays.toString(input));

            System.out.println("After removing duplicates   : " + Arrays.toString(removeDuplicates(input)));

        }

    }


    /*

     * Method to remove duplicates from array in Java, without using

     * Collection classes e.g. Set or ArrayList. Algorithm for this

     * method is simple, it first sort the array and then compare adjacent

     * objects, leaving out duplicates, which is already in the result.

     */

    public static int[] removeDuplicates(int[] numbersWithDuplicates) {


        // Sorting array to bring duplicates together      

        Arrays.sort(numbersWithDuplicates);     

      

        int[] result = new int[numbersWithDuplicates.length];

        int previous = numbersWithDuplicates[0];

        result[0] = previous;


        for (int i = 1; i < numbersWithDuplicates.length; i++) {

            int ch = numbersWithDuplicates[i];


            if (previous != ch) {

                result[i] = ch;

            }

            previous = ch;

        }

        return result;


    }

}


Output :

Array with Duplicates       : [1, 1, 2, 2, 3, 4, 5]

After removing duplicates   : [1, 0, 2, 0, 3, 4, 5]

Array with Duplicates       : [1, 1, 1, 1, 1, 1, 1]

After removing duplicates   : [1, 0, 0, 0, 0, 0, 0]

Array with Duplicates       : [1, 2, 3, 4, 5, 6, 7]

After removing duplicates   : [1, 2, 3, 4, 5, 6, 7]

Array with Duplicates       : [1, 2, 1, 1, 1, 1, 1]

After removing duplicates   : [1, 0, 0, 0, 0, 0, 2]


Explenation:

This Java program removes duplicates from an array of integers without using collections like Set or ArrayList. It implements a method called removeDuplicates, which sorts the input array, then iterates through it to compare adjacent elements, leaving out duplicates. The removed duplicates are replaced with default values (in this case, 0 since the array contains integers). The program demonstrates this functionality by applying it to various test arrays and printing the results. It uses SLF4J for logging purposes.


Credit: >Javarevisited


Suggested blogs:

>Testing react components using Hooks and Mocks

>How to mock a constant value in Python?

>Creating a pivot table by 6 month interval rather than year

>How to do PHP Decryption from Node.js Encryption

>How to Set up the Android emulator?

>How to Set up the local environment for Angular development?

>How to solve encoding issue when writing to a text file, with Python?

>Use Firebase Realtime Database with ASP.NET MVC App

>How to Install mariaDB client efficiently inside docker?

>Can I call an API to find out the random seed in Python `hash()` function?

>How remove residual lines after merge two regions using Geopandas in python?

>How to configure python in jmeter?


Submit
0 Answers