Learnitweb

Merge two unsorted arrays into a single sorted array using Java 8 streams

You can merge two unsorted arrays and sort them using Java 8 Streams with Stream.concat() and sorted().

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

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

        Integer[] mergedSortedArray = Stream.concat(Arrays.stream(array1), Arrays.stream(array2))
                .sorted()
                .toArray(Integer[]::new);

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

Output:

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

Explanation:

  • Arrays.stream(array1) → Converts array1 to a stream.
  • Stream.concat(..., ...) → Merges both streams.
  • sorted() → Sorts the merged stream in ascending order.
  • toArray(Integer[]::new) → Collects the sorted elements into a new array.
  • Arrays.toString(...) → Prints the array as a string.

Descending Order

If you want the merged array sorted in reverse order, just use:

.sorted(Comparator.reverseOrder())