如何在整数数组中使用Math.min和Math.max



我想在整数数组中找到最大值和最小值,但我无法使用它们。

Eclipse抛出此错误

类型Math中的方法min(int,int(不适用于arguments(int[](

我不能在数组中使用这些内置函数。

public static void main (String args[])
{
c_21 obj=new c_21();
int[] a =new int[3];
a[0]=1;
a[1]=5;
a[2]=6;
int max = Math.max(...a);
int min = Math.min(...a);
}

这些函数只需要两个参数。如果您想要数组的最小值,可以使用IntStream。

int[] a = { 1, 5, 6 };
int max = IntStream.of(a).max().orElse(Integer.MIN_VALUE);
int min = IntStream.of(a).min().orElse(Integer.MAX_VALUE);

您可以简单地在构建java中使用CollectionArrays来解决这个问题。你只需要导入它们并使用它。

请检查以下代码。

import java.util.Arrays;
import java.util.Collections;
public class getMinNMax {
public static void main(String[] args) {
Integer[] num = { 2, 11, 55, 99 };
int min = Collections.min(Arrays.asList(num));
int max = Collections.max(Arrays.asList(num));
System.out.println("Minimum number of array is : " + min);
System.out.println("Maximum number of array is : " + max);
}
}
  1. Math.max()/min()

    如果你真的想使用这2个功能,你可以做如下

    int max = Arrays.stream(a).reduce(Math::max).orElse(Integer.MAX_VALUE);
    int min = Arrays.stream(a).reduce(Math::min).orElse(Integer.MIN_VALUE);
    

  • IntStream内置功能

    int max = IntStream.of(a).max().orElse(Integer.MIN_VALUE);
    int min = IntStream.of(a).min().orElse(Integer.MAX_VALUE);
    

  • 使用简单的for loop

    int max = Integer.MIN_VALUE;
    int min = Integer.MAX_VALUE;
    for (int element : a) {
    max = Math.max(max, element);
    min = Math.min(min, element);
    }
    
  • 如果可能的话,在Apache Commons Lang中使用NumberUtils——那里有很多很棒的实用程序。

    NumberUtils.max(int[]);
    

    在您的情况下:

    int max = NumberUtils.max(a);
    

    或者你可以使用:

    int max = Collections.max(Arrays.asList(1,5,6));
    

    最新更新