Write a program to find the maximum element in an array.

Arrays.stream(int[]) gives an IntStream, and its max() method returns the largest value as an OptionalInt. Use getAsInt() when you are sure the array is not empty, or orElse() to supply a default.

Key Points

import java.util.Arrays;
import java.util.IntSummaryStatistics;

public class MaxInArray {

    static int findMax(int[] arr) {
        return Arrays.stream(arr).max().orElseThrow();
    }

    static int findMaxLoop(int[] arr) {
        int max = arr[0];
        for (int n : arr) {
            if (n > max) max = n;
        }
        return max;
    }

    public static void main(String[] args) {
        int[] arr = {12, 19, 20, 88, 0, 9};

        System.out.println(findMax(arr));
        System.out.println(findMaxLoop(arr));

        IntSummaryStatistics stats = Arrays.stream(arr).summaryStatistics();
        System.out.println("Min: " + stats.getMin() + ", Max: " + stats.getMax());
    }
}

Output

88

88

Min: 0, Max: 88

Good to Know

Mention summaryStatistics() when the interviewer also asks for the minimum or the average. It computes everything in a single pass, instead of streaming the array several times.

Interview Tip

A concise interview answer is

I use Arrays.stream(arr).max(), which returns an OptionalInt, and read it with getAsInt or orElseThrow. If I also need the minimum or average, summaryStatistics() gives everything in one pass, and a simple loop works just as well.

Last updated: 11 November 2026

Previous question: How do you use Optional in Java 8 to safely iterate over a list that may be null?

Next question: Write a program to count each character in a string.

More Stream API Coding Questions - Level II interview questions

All Stream API Coding Questions - Level II questions