260

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?

3
  • 11
    Array of primitive to array of containers would help: stackoverflow.com/questions/3770289/… followed by Collections.max(Arrays.asList()). Commented Mar 13, 2015 at 7:39
  • 5
    I just love how dumb the Java is Commented Jun 26, 2020 at 15:49
  • Arrays.asList won't work on an array of a primitive type\. Commented Apr 17, 2022 at 20:16

18 Answers 18

202

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.

Sign up to request clarification or add additional context in comments.

4 Comments

what is ArrayUtils
Arrays.asList() should be fine, but ArrayUtils.toObject() will copy each element of a to a new array of Character.
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.
For me this is the most relevant answer, because of clarity and COMPATIBILITY! Thanks!
176

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.

Comments

62

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.

2 Comments

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/…)
This is the best solution of everything here. Avoids all that java.util.Arrays#asList varargs confusion.
23

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.

6 Comments

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].
This is a legitimate and useful way of solving the problem. What's the disadvantage of using it compared to the other ones?
@alex time complexity - sorting is at best an O(nlogn) affair, while Michael Rutherfurd approach is O(n).
We dont need sort as single iteration over list is enough to find min and max.
@akhil_mittal but this requires more code than a sort, because there is no Java standard method to do this iteration
|
20

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

5 Comments

Collections.min(myCollection); If you want to use it for arrays, you can do it like Collections.min(Arrays.asList(myArray));
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.html
@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.
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/…
@Christoph Christoph is right, it is inefficient and stupid to transform an array to an Collection, for min max search.
12

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

2 Comments

You should use double max = Double.NEGATIVE_INFINITY; instead of double max = Double.MIN_VALUE; As MIN_VALUE for double is positive
... or you could set max to the first item in the array, and iterate from the 2nd item, see my answer.
4

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.)

1 Comment

Best answer because using an IntStream to index the array works with any numeric primitive array type, not just int[]. You can use mapToLong or mapToDouble instead of map if the array is a long[] or float[]/double[], respectively.
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;
    }

1 Comment

This is for numbers int but the question is asking for primitive values int, long, char, byte....
3
 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);
    }
}

1 Comment

only works for int[] (example in question uses char[])
2

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

Comments

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

Comments

1

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

1 Comment

little problem - this only works for int[], long[] and double[]; not for the other arrays of primitive (example in question uses char[])
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);

2 Comments

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.
just a small problem - this only works for int[], long[] and double[]; not for the other arrays of primitive (example in question uses char[])
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].

1 Comment

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

1 Comment

;-) That’s “Not completely serious” alright. Hesitating to upvote…
0

Java provides numeric streams of int, long and double. If you have an array of one of those, you can find the min or max using Arrays.stream().

A comprehensive solution to the problem of reductions over primitive arrays is rather than implement min(), max() etc. for each array type, to instead implement the missing overrides of Arrays.stream(). Then you can use numeric stream methods such as .min(), .max(), .reduce(), and .generateStatistics(). Using a numeric stream avoids the overhead of sorting the array, converting all of the elements to wrapper types, or converting the whole array to int[] or double[].

public static IntStream stream(final byte[] bytes) {
    return IntStream.range(0, bytes.length).map(i -> bytes[i]);
}
public static IntStream stream(final char[] chars) {
    return IntStream.range(0, chars.length).map(i -> chars[i]);
}
public static IntStream stream(final short[] shorts) {
    return IntStream.range(0, shorts.length).map(i -> shorts[i]);
}
public static DoubleStream stream(final float[] floats) {
    return IntStream.range(0, floats.length).mapToDouble(i -> floats[i]);
}

The overhead of converting to int should be minimal since the JVM represents smaller integral values as int anyway, except in arrays.

The overhead of converting from float to double is very slightly larger, so if you really care about performance you still might want to iterate over the array. Since there are float overrides for Math::max, Math::min , and so on, you could use this reduce method with them:


@FunctionalInterface
public interface FloatBinaryOperator {
    float applyAsFloat(float left, float right);
}

public static float reduce(final float[] floats, final float identity, final FloatBinaryOperator operator) {
    float result = identity;
    for (float element : floats) {
        result = operator.applyAsFloat(result, element);
    }
    return result;
}

float[] floats = getFloats();
float min = reduce(floats, Float.POSITIVE_INFINITY, Math::min);
float max = reduce(floats, Float.NEGATIVE_INFINITY, Math::max);

I haven't benchmarked converting to DoubleStream vs using this reduce() method. As always, do your own profiling before making performance decisions.

Comments

-1

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

1 Comment

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.
-1
    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");
    }
}

1 Comment

What question does this answer, and how?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.