1

I have, in Java, a double[] foo.

Is there a library function for pulling out the minimum value in this array? I know I can build one, but that's not a good practice if a library function is available. There's nothing in java.util.Arrays.

(In C++ we have std::min_element etc. and even a new function in C++11 to get the minimum and maximum out at the same time!)

Eran
  • 387,369
  • 54
  • 702
  • 768
P45 Imminent
  • 8,319
  • 4
  • 35
  • 78

4 Answers4

6

Assuming Java 8:

double[] arr = { 1.0, 2.0 };
double min = DoubleStream.of(arr)
                         .min()
                         .getAsDouble();
McDowell
  • 107,573
  • 31
  • 204
  • 267
  • 1
    +1, pretty (and is the best answer to my question given that Java 8 is the current standard and I tagged as Java) but don't have Java 8 yet. – P45 Imminent Oct 23 '14 at 12:33
4

Well, Collections class has such method.

You can write

Double[] arr = {0.5,0.7};
System.out.println("min = " + Collections.min(Arrays.asList(arr)));

Or to make it shorter :

System.out.println("min = " + Collections.min(Arrays.asList(-67,-89,64,34)));
Eran
  • 387,369
  • 54
  • 702
  • 768
  • 1
    +1 but have reservations about converting `double[]` to `Double[]` – P45 Imminent Oct 23 '14 at 12:17
  • 1
    @SlodgeMonster Arrays.asList on a double array will return a List with a single double[] element, so you must use Double array. – Eran Oct 23 '14 at 12:20
  • Thanks, I went for this in the end having changed my `double[]` to a `Double[]`. `Collections.min(Arrays.asList(arr))` is standard Java and doesn't take a deep copy. – P45 Imminent Oct 23 '14 at 12:32
1

You can convert double[] to Double[] using ArrayUtils.toObject.
Then convert array to list with Arrays.asList and find minimum with Collections.min.

double[] d = new double[] {1, 2, 3};
Double minValue = Collections.min(Arrays.asList(ArrayUtils.toObject(d)));
System.out.println(minValue);
Alex
  • 11,451
  • 6
  • 37
  • 52
1

You can use com.google.common.primitives.Doubles

 double[] arr = { 4.3, 4.9 };
 double min = Doubles.min(arr);
 //OR
 //double min = Doubles.min(4.3, 4.9);
akash
  • 22,664
  • 11
  • 59
  • 87