Home » Java » java – Eliminate duplicates in Array-Exceptionshub

java – Eliminate duplicates in Array-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

(Eliminate duplicates) Write a method that returns a new array by eliminating the
duplicate values in the array using the following method header:

public static int[] eliminateDuplicates(int[] list)

Write a test program that reads in 10 integers, invokes the method, and displays the distinct numbers separated by exactly one space. Here is a sample run of the
program:
Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
The distinct numbers are: 1 2 3 6 4 5

package bucky;

import java.util.Scanner;

public class Arrays {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        System.out.print("Enter ten numbers: ");

        int[] list = new int[10];

        for (int i = 0; i < list.length; i++) {
            list[i] = in.nextInt();
        }
        eliminateDuplicates(list);

        System.out.print("The distinct numbers are: ");
        for (int i = 0; i < list.length; i++) {
            System.out.print(list[i]);
        }
    }

    public static int[] eliminateDuplicates(int[] list) {

        int count = 0;
        int j = 0;
        int[] nArray = new int[list.length];
        while (j < list.length) {
            for (int i = 1; i < list.length; i++) {
                int low = list[j];
                if (list[i] == low) {
                    count++;
                } else {
                    nArray[i] = low;
                }
            }
            j++;
        }
        return nArray;
    }
}
How to&Answers:

Array can be simply converted to a HashSet which eliminates duplicate automatically.

Set list2 = Arrays.stream(list).boxed().collect(Collectors.toSet());
System.out.print(“The distinct numbers are: ” + list2);