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
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)
You could easily do it with an IntStream
and the max()
method.
public static int maxValue(final int[] intArray) {
return IntStream.range(0, intArray.length).map(i -> intArray[i]).max().getAsInt();
}
range(0, intArray.length)
- To get a stream with as many elements as present in the intArray
.
map(i -> intArray[i])
- Map every element of the stream to an actual element of the intArray
.
max()
- Get the maximum element of this stream as OptionalInt
.
getAsInt()
- Unwrap the OptionalInt
. (You could also use here: orElse(0)
, just in case the OptionalInt
is empty.)
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.
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);
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;
}
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.