Languages
[Edit]
EN

Java - min value in array

3 points
Created by:
Warren-X
323

This article will show you how to find the minimum value in an array in Java.

Quick solution:

Integer[] numbersArray = { 1, 5, 2, 16, -5};

int min = Collections.min( Arrays.asList(numbersArray) );
System.out.println(  min  ); // -5

 

Practical examples

1. With Collections.min method

public class MathExample {

    public static void main(String[] args) {
        Integer[] numbersArray = { 1, 5, 2, 16, -5};

        int min = Collections.min( Arrays.asList(numbersArray) );
        System.out.println(  min  ); // -5
    }
}

2. By comparing all the elements in the array

public class MathExample {

    static double min(double[] array) {
        double result = Double.POSITIVE_INFINITY;
        for (double currentNumber : array) {
            if (result > currentNumber) result = currentNumber;
        }
        return result;
    }

    public static void main(String[] args) {
        double[] numbersArray = {1.4, 5.0, 2.2, 16.0, -5.0};

        System.out.println(  min(numbersArray) ); // -5.0
    }
}

See also

  1. Java - Math.min() method example

  2. Maxima and minima - Wikipedia

Java - Arrays (popular problems)

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join