Java program to find max and min value in an array

Hey guys!!! Welcome to flower brackets blog. In today’s post let us learn java program to find max and min value in an array.

To find max and min value in an array use max() and min() methods of java.util.Collections class.

Also read – convert decimal to octal java program

Meanwhile in java.utils.Arrays class we have function “aslist()”. This function returns a fixed-size list backed by the specified array.

Also this method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray().

Here, I’m gonna show you how to find max and min value in an array in java.

import java.util.Arrays;
import java.util.Collections;

public class MaxMinDemo
{
   public static void main(String[] args)
   {
      Integer numbers[] = { 63, 56, 36, 60, 15, 52 };
      int minimum = Collections.min(Arrays.asList(numbers));
      int maximum = Collections.max(Arrays.asList(numbers));
      // print minimum and maximum number 
      System.out.println("Minimum number : " + minimum); 
      System.out.println("Maximum number : " + maximum);
   }
}

Output:

Minimum number : 15
Maximum number : 63


Similarly we can find largest in an array using iterative method and java 8 stream. Let’s see java program,

// using iterative method
public class LargestInArrayDemo 
{
   static int arrNumber[] = {65, 235, 369, 36, 238};
   static int findLargest() 
   {
      // initializing max element 
      int max = arrNumber[0];
      // traversing array elements from second 
      // and comparing every element with current 
      for(int a = 1; a < arrNumber.length; a++)
      {
         if(arrNumber[a] > max)
         {
            max = arrNumber[a];
         }
      }
      return max; 
   }

   public static void main(String[] args) 
   { 
      System.out.println("Largest number : " + findLargest());
   }
}

Output:

Largest number : 369


// using java 8 stream
import java.util.Arrays;

public class LargestUsingStream 
{
   public static void main(String[] args) 
   {
      int arrNumber[] = {65, 235, 369, 36, 238}; 
      int maximum = Arrays.stream(arrNumber).max().getAsInt(); 
      System.out.println("Largest number : " + maximum);
   }
}

Output:

Largest number : 369

Related Posts