问题
编写一个函数来确定数组中的最小/最大值是很简单的,例如:
/**
*
* @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;
}
但这不是已经在某处做过的吗?
#1 热门回答(137 赞)
使用Commons Lang(转换)集合(最小/最大)
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));
}
}
请注意,Arrays.asList()
包含了底层数组,因此它不应该是内存密集型的,它不应该对数组的元素执行复制。
#2 热门回答(53 赞)
TheGoogle Guava library在其Chars,Ints,Longs等类中有min和max方法。
所以你可以简单地使用:
Chars.min(myarray)
不需要转换,并且可能是有效实施的。
#3 热门回答(39 赞)
你只需使用新的Java 8Stream
s,但你必须使用int
。
实用程序classArrays
的stream
方法为你提供了aIntStream
,你可以使用min
方法。你也可以做max
,sum
,average
,...
ThegetAsInt
方法用于从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)
}
}
==更新==
如果执行时间很重要,并且只想一次使用summaryStatistics()
方法,那么只想执行数据
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);
}
}
这种方法可以提供比经典循环更好的性能,因为summaryStatistics
方法是areduction operation并且它允许并行化。