Learnitweb

Merge two unsorted arrays into a single sorted array without duplicates

You can merge two unsorted arrays into a single sorted array without duplicates using Java 8 Streams. The key steps are:

  • Use Stream.concat() (for object arrays) or IntStream.concat() (for primitive arrays) to merge.
  • Use distinct() to remove duplicates.
  • Use sorted() to sort the merged array.

For Integer Object Arrays (Integer[])

import java.util.Arrays;
import java.util.stream.Stream;

public class MergeSortRemoveDuplicates {
    public static void main(String[] args) {
        Integer[] array1 = {5, 2, 9, 1, 2};
        Integer[] array2 = {8, 3, 7, 4, 3};

        Integer[] mergedSortedArray = Stream.concat(Arrays.stream(array1), Arrays.stream(array2))
                .distinct() // Remove duplicates
                .sorted()   // Sort the elements
                .toArray(Integer[]::new);

        System.out.println(Arrays.toString(mergedSortedArray));
    }
}

Output:

[1, 2, 3, 4, 5, 7, 8, 9]

For Primitive int Arrays (int[]):

Since IntStream doesn’t support distinct() on boxed values directly, use:

import java.util.Arrays;
import java.util.stream.IntStream;

public class MergeSortRemoveDuplicatesPrimitive {
    public static void main(String[] args) {
        int[] array1 = {5, 2, 9, 1, 2};
        int[] array2 = {8, 3, 7, 4, 3};

        int[] mergedSortedArray = IntStream.concat(Arrays.stream(array1), Arrays.stream(array2))
                .distinct() // Remove duplicates
                .sorted()   // Sort the elements
                .toArray();

        System.out.println(Arrays.toString(mergedSortedArray));
    }
}

Output:

[1, 2, 3, 4, 5, 7, 8, 9]