Code Logo

Find Extremes with Collections.max min

Published at25 Jul 2026
Collections Framework Easy 0 views
Like0

Write a Java function that takes a List and returns an int[] with two elements: the maximum value (using Collections.max()) and the minimum value (using Collections.min()). For an empty list, return an array of zeros.

Collections.max() and Collections.min() are static utility methods that return the maximum and minimum element of a collection according to the natural ordering of its elements. The elements must implement the Comparable interface (which Integer does). These methods throw NoSuchElementException if the collection is empty.

The Collections class in java.util provides many static utility methods for collections: sort(), reverse(), shuffle(), binarySearch(), frequency(), disjoint(), unmodifiableList(), synchronizedList(), and more. These methods operate on the Collection interface and its subtypes (List, Set, Queue).

Time complexity is O(n) where n is the list size, as both max() and min() iterate through all elements. Space complexity is O(1). The methods use the iterator of the collection to traverse elements.

Edge cases include empty lists (handle with if-check to avoid NoSuchElementException), single-element lists (both max and min return the same element), lists with duplicate values, and lists with all identical values.

Example Input & Output

Example 1
Input
[10]
Output
[10,10]
Explanation

Single element

Example 2
Input
[7,7,7]
Output
[7,7]
Explanation

All same

Example 3
Input
[-5,-2,-8]
Output
[-2,-8]
Explanation

Max=-2, Min=-8

Example 4
Input
[3,1,4,1,5]
Output
[5,1]
Explanation

Max=5, Min=1

Example 5
Input
[]
Output
[0,0]
Explanation

Empty returns zeros

Algorithm Flow

Recommendation Algorithm Flow for Find Extremes with Collections.max min
Recommendation Algorithm Flow for Find Extremes with Collections.max min

Solution Approach

import java.util.List;
import java.util.Collections;

class Solution {
    public int[] solution(List<Integer> nums) {
        if (nums.isEmpty()) return new int[]{0, 0};
        int max = Collections.max(nums);
        int min = Collections.min(nums);
        return new int[]{max, min};
    }
}

Best Answers

java - Approach 1
import java.util.List;
import java.util.Collections;

class Solution {
    public int[] solution(List<Integer> nums) {
        if (nums.isEmpty()) return new int[]{0, 0};
        int max = Collections.max(nums);
        int min = Collections.min(nums);
        return new int[]{max, min};
    }
}