Finding the max/min value in an array of primitives using Java
Asked Answered
D

18

249

It's trivial to write a function to determine the min/max value in an array, such as:

/**
 * 
 * @param chars
 * @return the max value in the array of chars
 */
private static int maxValue(char[] chars) {
    int max = chars[0];
    for (int ktr = 0; ktr < chars.length; ktr++) {
        if (chars[ktr] > max) {
            max = chars[ktr];
        }
    }
    return max;
}

but isn't this already done somewhere?

Dairymaid answered 27/9, 2009 at 20:7 Comment(3)
Array of primitive to array of containers would help: #3770789 followed by Collections.max(Arrays.asList()).Cryptozoite
I just love how dumb the Java isAdrastus
Arrays.asList won't work on an array of a primitive type\.Spendable
M
201

Using Commons Lang (to convert) + Collections (to min/max)

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

import org.apache.commons.lang.ArrayUtils;

public class MinMaxValue {

    public static void main(String[] args) {
        char[] a = {'3', '5', '1', '4', '2'};

        List b = Arrays.asList(ArrayUtils.toObject(a));

        System.out.println(Collections.min(b));
        System.out.println(Collections.max(b));
   }
}

Note that Arrays.asList() wraps the underlying array, so it should not be too memory intensive and it should not perform a copy on the elements of the array.

Mikelmikell answered 28/9, 2009 at 8:43 Comment(3)
what is ArrayUtilsVail
Arrays.asList() should be fine, but ArrayUtils.toObject() will copy each element of a to a new array of Character.Maquis
Arrays.asList(a) doesn't work. You can't make a list of primitives (List<char> in this case). First you need to convert the primitive values to objects and that's why ArrayUtils.toObject is used.Garvy
H
170

You can simply use the new Java 8 Streams but you have to work with int.

The stream method of the utility class Arrays gives you an IntStream on which you can use the min method. You can also do max, sum, average,...

The getAsInt method is used to get the value from the OptionalInt

import java.util.Arrays;

public class Test {
    public static void main(String[] args){
        int[] tab = {12, 1, 21, 8};
        int min = Arrays.stream(tab).min().getAsInt();
        int max = Arrays.stream(tab).max().getAsInt();
        System.out.println("Min = " + min);
        System.out.println("Max = " + max)
    }

}

==UPDATE==

If execution time is important and you want to go through the data only once you can use the summaryStatistics() method like this

import java.util.Arrays;
import java.util.IntSummaryStatistics;

public class SOTest {
    public static void main(String[] args){
        int[] tab = {12, 1, 21, 8};
        IntSummaryStatistics stat = Arrays.stream(tab).summaryStatistics();
        int min = stat.getMin();
        int max = stat.getMax();
        System.out.println("Min = " + min);
        System.out.println("Max = " + max);
    }
}

This approach can give better performance than classical loop because the summaryStatistics method is a reduction operation and it allows parallelization.

Heaps answered 7/6, 2015 at 10:26 Comment(0)
G
61

The Google Guava library has min and max methods in its Chars, Ints, Longs, etc. classes.

So you can simply use:

Chars.min(myarray)

No conversions are required and presumably it's efficiently implemented.

Gambell answered 1/11, 2009 at 19:50 Comment(2)
It's implemented more or less like in the question except it throws an IllegalArgumentException for an array of length 0. (code.google.com/p/guava-libraries/source/browse/trunk/src/com/…)Cloyd
This is the best solution of everything here. Avoids all that java.util.Arrays#asList varargs confusion.Marine
N
25

By sorting the array, you get the first and last values for min / max.

import java.util.Arrays;

public class apples {

  public static void main(String[] args) {
    int a[] = {2,5,3,7,8};
    Arrays.sort(a);

    int min =a[0];
    System.out.println(min);

    int max= a[a.length-1];
    System.out.println(max);
  }
    
}

Although the sorting operation is more expensive than simply finding min/max values with a simple loop. But when performance is not a concern (e.g. small arrays, or your the cost is irrelevant for your application), it is a quite simple solution.

Note: the array also gets modified after this.

Navarro answered 19/4, 2014 at 11:53 Comment(5)
I think what this means to say is that if you sort the array (in ascending order), by definition, the minimum value will always be at the first position, a[0], and the maximum value will always be at the last position, [a.length-1].Snake
This is a legitimate and useful way of solving the problem. What's the disadvantage of using it compared to the other ones?Verruca
@alex time complexity - sorting is at best an O(nlogn) affair, while Michael Rutherfurd approach is O(n).Trolley
We dont need sort as single iteration over list is enough to find min and max.Allowed
@Allowed but this requires more code than a sort, because there is no Java standard method to do this iterationGattis
S
21

Yes, it's done in the Collections class. Note that you will need to convert your primitive char array to a Character[] manually.

A short demo:

import java.util.*;

public class Main {

    public static Character[] convert(char[] chars) {
        Character[] copy = new Character[chars.length];
        for(int i = 0; i < copy.length; i++) {
            copy[i] = Character.valueOf(chars[i]);
        }
        return copy;
    }

    public static void main(String[] args) {
        char[] a = {'3', '5', '1', '4', '2'};
        Character[] b = convert(a);
        System.out.println(Collections.max(Arrays.asList(b)));
    }
}
Swirl answered 27/9, 2009 at 20:10 Comment(5)
Collections.min(myCollection); If you want to use it for arrays, you can do it like Collections.min(Arrays.asList(myArray));Peepul
converting a char [] to a Character [] only to determine the maximum is quite inefficient - better create a utility class with static methods for each primitive type similar to java.util.Arrays: java.sun.com/javase/6/docs/api/java/util/Arrays.htmlLuvenialuwana
@Christoph: yes, if the size of the array is large, I would agree. Simply stating it is "inefficient" does not make sense if the application in question makes many database calls and/or I/O operations and the size of the array is (relative) small.Swirl
you should use Character.valueOf(chars[i]) instead of new Character(chars[i]) for performance reasons: java.sun.com/javase/6/docs/api/java/lang/…Luvenialuwana
@Luvenialuwana Christoph is right, it is inefficient and stupid to transform an array to an Collection, for min max search.Cleopatra
S
11

I have a little helper class in all of my applications with methods like:

public static double arrayMax(double[] arr) {
    double max = Double.NEGATIVE_INFINITY;

    for(double cur: arr)
        max = Math.max(max, cur);

    return max;
}
Slider answered 13/10, 2016 at 21:30 Comment(2)
You should use double max = Double.NEGATIVE_INFINITY; instead of double max = Double.MIN_VALUE; As MIN_VALUE for double is positiveBronchitis
... or you could set max to the first item in the array, and iterate from the 2nd item, see my answer.Regularly
L
3

Here's a utility class providing min/max methods for primitive types: Primitives.java

int [] numbers= {10,1,8,7,6,5,2};
    int a=Integer.MAX_VALUE;
    for(int c:numbers) {
        a=c<a?c:a;
        }
        
    System.out.println("Lowest value is"+a);
Luvenialuwana answered 27/9, 2009 at 21:12 Comment(0)
E
3

You could easily do it with an IntStream and the max() method.

Example

public static int maxValue(final int[] intArray) {
  return IntStream.range(0, intArray.length).map(i -> intArray[i]).max().getAsInt();
}

Explanation

  1. range(0, intArray.length) - To get a stream with as many elements as present in the intArray.

  2. map(i -> intArray[i]) - Map every element of the stream to an actual element of the intArray.

  3. max() - Get the maximum element of this stream as OptionalInt.

  4. getAsInt() - Unwrap the OptionalInt. (You could also use here: orElse(0), just in case the OptionalInt is empty.)

Elaboration answered 26/8, 2015 at 15:29 Comment(0)
R
3
    public int getMin(int[] values){
        int ret = values[0];
        for(int i = 1; i < values.length; i++)
            ret = Math.min(ret,values[i]);
        return ret;
    }
Regularly answered 6/3, 2018 at 10:49 Comment(1)
This is for numbers int but the question is asking for primitive values int, long, char, byte....Bina
P
2
import java.util.Random;

public class Main {

public static void main(String[] args) {
   int a[] = new int [100];
   Random rnd = new Random ();

    for (int i = 0; i< a.length; i++) {
        a[i] = rnd.nextInt(99-0)+0;
        System.out.println(a[i]);
    }

    int max = 0;          

    for (int i = 0; i < a.length; i++) {
        a[i] = max;


        for (int j = i+1; j<a.length; j++) {
            if (a[j] > max) {
               max = a[j];
            }

        }
    }

    System.out.println("Max element: " + max);
}
}
Parley answered 1/10, 2013 at 16:29 Comment(0)
C
2

A solution with reduce():

int[] array = {23, 3, 56, 97, 42};
// directly print out
Arrays.stream(array).reduce((x, y) -> x > y ? x : y).ifPresent(System.out::println);

// get the result as an int
int res = Arrays.stream(array).reduce((x, y) -> x > y ? x : y).getAsInt();
System.out.println(res);
>>
97
97

In the code above, reduce() returns data in Optional format, which you can convert to int by getAsInt().

If we want to compare the max value with a certain number, we can set a start value in reduce():

int[] array = {23, 3, 56, 97, 42};
// e.g., compare with 100
int max = Arrays.stream(array).reduce(100, (x, y) -> x > y ? x : y);
System.out.println(max);
>>
100

In the code above, when reduce() with an identity (start value) as the first parameter, it returns data in the same format with the identity. With this property, we can apply this solution to other arrays:

double[] array = {23.1, 3, 56.6, 97, 42};
double max = Arrays.stream(array).reduce(array[0], (x, y) -> x > y ? x : y);
System.out.println(max);
>>
97.0
Confiscable answered 26/2, 2019 at 6:3 Comment(0)
H
2
 IntStream.of(a).max().getAsInt()

Example:

import java.util.stream.IntStream;
public class Solution {
    public static void main(String[] args) {
        int[] a = {3, 7, 5, 2};
        int max = IntStream.of(a).max().getAsInt();
        System.out.println(max);
    }
}
Handiness answered 26/7, 2023 at 1:14 Comment(0)
A
1

Example with float:

public static float getMaxFloat(float[] data) {

    float[] copy = Arrays.copyOf(data, data.length);
    Arrays.sort(copy);
    return copy[data.length - 1];
}

public static float getMinFloat(float[] data) {

    float[] copy = Arrays.copyOf(data, data.length);
    Arrays.sort(copy);
    return copy[0];
}
Apocarpous answered 11/6, 2016 at 10:28 Comment(3)
While your solution will work, but it will increase the time complexity to O(nlogn) while min can be found easily in O(n) by using other answers.Hippel
simply crazy to use a sort in this situation.Regularly
It can be useful when the first n>1 smallest/largest value is needed, with some repairs.Soutine
O
1

Here we can use Arrays.stream() to get Max Value from a primitive array in Java.

int [] numbers = {10,1,8,7,6,5,2};
int maxValue = Arrays.stream(numbers).max().getAsInt();
System.out.println(maxValue);
Onanism answered 29/3, 2024 at 15:57 Comment(1)
Other questions have provided this as part of an answer, but none as the main point of the answer or as succinctly. +1 from me, and I think this makes sense as its own distinct answer from the rest.Workaday
L
0

Pass the array to a method that sorts it with Arrays.sort() so it only sorts the array the method is using then sets min to array[0] and max to array[array.length-1].

Lymphocytosis answered 12/11, 2013 at 5:8 Comment(1)
It's probably worth noting that a) this modifies the array, and b) for large arrays it's a more expensive solution O(nlog n) rather than O(n)Quartan
D
0

The basic way to get the min/max value of an Array. If you need the unsorted array, you may create a copy or pass it to a method that returns the min or max. If not, sorted array is better since it performs faster in some cases.

public class MinMaxValueOfArray {
    public static void main(String[] args) {
        int[] A = {2, 4, 3, 5, 5};
        Arrays.sort(A);
        int min = A[0];
        int max = A[A.length -1];
        System.out.println("Min Value = " + min);        
        System.out.println("Max Value = " + max);
    }
}
Dulcimer answered 18/6, 2015 at 9:30 Comment(1)
The problem with sorting is that it has an O(n log n) overhead for a O(n) problem. But this is better than the other three "sort the array" answers already given.Viviennevivify
R
0

Here is a solution to get the max value in about 99% of runs (change the 0.01 to get a better result):

public static double getMax(double[] vals){
    final double[] max = {Double.NEGATIVE_INFINITY};

    IntStream.of(new Random().ints((int) Math.ceil(Math.log(0.01) / Math.log(1.0 - (1.0/vals.length))),0,vals.length).toArray())
            .forEach(r -> max[0] = (max[0] < vals[r])? vals[r]: max[0]);

    return max[0];
}

(Not completely serious)

Roer answered 2/11, 2018 at 13:34 Comment(1)
;-) That’s “Not completely serious” alright. Hesitating to upvote…Regolith
F
0
    int[] arr = {1, 2, 3};

    List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());
    int max_ = Collections.max(list);
    int i;
    if (max_ > 0) {
        for (i = 1; i < Collections.max(list); i++) {
            if (!list.contains(i)) {
                System.out.println(i);
                break;
            }
        }
        if(i==max_){
            System.out.println(i+1);
        }
    } else {
        System.out.println("1");
    }
}
Froth answered 19/1, 2021 at 22:7 Comment(1)
What question does this answer, and how?Frizette

© 2022 - 2025 — McMap. All rights reserved.