Find Minimum and Maximum Elements in an Array in Java



Finding the minimum and maximum elements in an array can be done using built-in utility methods or by manually iterating through the array in Java. The following are the methods for searching the minimum and the maximum element in an array

  • Using Collections.min() and Collections.max() methods

  • Using for loop

Using Collections.min() and Collections.max() Methods

The Collections.min() and Collections.max() methods are part of the java.util.Collections class and are used to find the minimum and maximum elements from a collection, such as a list or set.

Collections.min() Method

The min() method of java.util.Collections class is used to return the minimum element of the given collection.

Syntax

public static <T 
  extends Object & Comparable<? super T>> T 
    min(Collection<? extends T> coll)
  

Collections.max() Method

The max() method of java.util.Collections class is used to return the maximum element of the given collection.

Syntax

public static <T extends Object & Comparable> T
  max(Collection coll)
  

Example

This example shows how to search the minimum and maximum element in an array by using Collection.max() and Collection.min() methods of Collection class

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

public class Main {
   public static void main(String[] args) {
      Integer[] numbers = { 8, 2, 7, 1, 4, 9, 5};
      int min = (int) Collections.min(Arrays.asList(numbers));
      int max = (int) Collections.max(Arrays.asList(numbers));
      
      System.out.println("Min number: " + min);
      System.out.println("Max number: " + max);
   }
}

Output

Min number: 1
Max number: 9

Using for Loop

The for loop is used to iterate through the array, comparing each element to find the smallest and largest values. The for loop is used to repeat a block of code for a specified number of iterations.

Example

The following is an example of the minimum and the maximum element in an array.

public class HelloWorld {
   public static void main(String[] args) {
      int numbers[] = new int[]{8, 2, 7, 1, 4, 9, 5};
      int s = numbers[0];
      int l = numbers[0];
      
      for(int i = 1; i < numbers.length; i++) {
         if(numbers[i] > l)l = numbers[i];
         else if (numbers[i] < s)s = numbers[i];
      } 
      System.out.println("Largest Number is : " + l);
      System.out.println("Smallest Number is : " + s);
   }
}

Output

Largest Number is : 9
Smallest Number is : 1     .
java_arrays.htm
Advertisements