Write a Java 8 program to sort an array and convert it into a stream.

First sort the array with Arrays.sort() (or Arrays.parallelSort() for very large arrays), then turn it into a stream with Arrays.stream(). Alternatively, convert the array to a stream and let sorted() do the sorting.

Key Points

import java.util.Arrays;
import java.util.stream.Collectors;

public class SortArrayToStream {

    public static void main(String[] args) {

        int[] arr = {99, 55, 203, 99, 4, 91};

        // 1. Sort in place, then stream
        int[] copy = arr.clone();
        Arrays.sort(copy);
        String sorted = Arrays.stream(copy)
                              .mapToObj(String::valueOf)
                              .collect(Collectors.joining(" "));
        System.out.println(sorted);

        // 2. Let the stream sort (original array untouched)
        Arrays.stream(arr)
              .sorted()
              .forEach(n -> System.out.print(n + " "));
        System.out.println();
        System.out.println(Arrays.toString(arr));
    }
}

Output

4 55 91 99 99 203

4 55 91 99 99 203

[99, 55, 203, 99, 4, 91]

Good to Know

A good point to raise is when to use parallelSort(). It only pays off for large arrays (tens of thousands of elements). For small arrays the overhead of splitting the work makes it slower than Arrays.sort().

Interview Tip

A concise interview answer is

I sort the array with Arrays.sort and then call Arrays.stream on it, which gives an IntStream. Alternatively, Arrays.stream(arr).sorted() returns a sorted stream without changing the original array; parallelSort only helps for very large arrays.

Last updated: 11 November 2026

Previous question: Write a Java 8 program that cubes each list element and keeps only results greater than 50.

Next question: How do you convert strings to uppercase using map() in Java 8?

More Stream API Coding Questions - Level II interview questions

All Stream API Coding Questions - Level II questions