编写一个函数来确定数组中的最小/最大值是很简单的,例如:

/**
 * 
 * @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;
}

但这不是已经在某个地方做过了吗?


当前回答

通过对数组排序,可以得到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);
  }
    
}

尽管排序操作比用简单的循环查找最小/最大值更昂贵。但当性能不是问题时(例如,小数组,或者成本与应用程序无关),这是一个相当简单的解决方案。

注意:数组在此之后也会被修改。

其他回答

使用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

在上面的代码中,reduce()以可选格式返回数据,您可以通过getAsInt()将其转换为int。

如果我们想将最大值与某个数字进行比较,我们可以在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

在上面的代码中,当reduce()以标识(起始值)作为第一个参数时,它将返回与标识相同格式的数据。有了这个属性,我们可以将这个解决方案应用到其他数组:

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

谷歌Guava库在其char, int, long等类中有min和max方法。

所以你可以简单地使用:

Chars.min(myarray)

不需要转换,并且可以有效地实现。

使用Commons Lang(转换)+ Collections(到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));
   }
}

注意,Arrays.asList()包装底层数组,因此它不应该占用太多内存,也不应该对数组的元素执行复制。

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

通过对数组排序,可以得到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);
  }
    
}

尽管排序操作比用简单的循环查找最小/最大值更昂贵。但当性能不是问题时(例如,小数组,或者成本与应用程序无关),这是一个相当简单的解决方案。

注意:数组在此之后也会被修改。