Open In App
Related Articles

Find max or min value in an array of primitives using Java

Improve Article
Improve
Save Article
Save
Like Article
Like

Java as a whole is a language that generally requires a lot of coding to execute specific tasks. Hence, having shorthand for several utilities can be beneficial. One such utility, to find maximum and minimum element in array is explained in this article using “aslist()“. aslist() type casts a list from the array passed in its argument. This function is defined in “Java.utils.Arrays“. 
To get the minimum or maximum value from the array we can use the Collections.min() and Collections.max() methods. 
But as this method requires a list type of data we need to convert the array to list first using above explained “aslist()” function.

Note:  “The array you are passing to the Arrays.asList() must have a return type of Integer or whatever class you want to use”, since the Collections.sort() accepts ArrayList object as a parameter. 

Note: If you use type int while declaring the array you will end up seeing this error: “no suitable method found for min(List<int[]>)”

Java




// Java code to demonstrate how to
// extract minimum and maximum number
// in 1 line.
import java.util.Arrays;
import java.util.Collections;
 
public class MinNMax {
    public static void main(String[] args)
    {
 
        // Initializing array of integers
        Integer[] num = { 2, 4, 7, 5, 9 };
 
        // using Collections.min() to
        // find minimum element
        // using only 1 line.
        int min = Collections.min(Arrays.asList(num));
 
        // using Collections.max()
        // to find maximum element
        // using only 1 line.
        int max = Collections.max(Arrays.asList(num));
 
        // printing minimum and maximum numbers
        System.out.println("Minimum number of array is : "
                           + min);
        System.out.println("Maximum number of array is : "
                           + max);
    }
}


Output

Minimum number of array is : 2
Maximum number of array is : 9

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 21 Jun, 2022
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials