Find Extremes with Collections.max min
Write a Java function that takes a List
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
Single element
All same
Max=-2, Min=-8
Max=5, Min=1
Empty returns zeros
Algorithm Flow

Solution Approach
Best Answers
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};
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
