English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Find the maximum and minimum values in a primitive array using Java

This example demonstrates how to use the Collection class's Collection.max() and Collection.min() methods to search for the smallest and largest elements in an array.

Example

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 Result

The following result will be produced by the above code example.

Min number: 1
Max number: 9

Another example of finding the smallest and largest elements in an array.

Example

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);
   }
}

The following result will be produced by the above code example.

Largest Number is : 9
Smallest Number is : 1