在使用Java的原语数组中找到最大/最小值。

时间:2022-09-28 10:06:12

It's trivial to write a function to determine the min/max value in an array, such as:

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

/**
 * 
 * @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?

但这不是已经在某个地方完成了吗?

14 个解决方案

#1


134  

Using Commons Lang (to convert) + Collections (to min/max)

使用Commons Lang(转换)+集合(到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.

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

#2


53  

The Google Guava library has min and max methods in its Chars, Ints, Longs, etc. classes.

谷歌Guava库在其Chars、Ints、Longs等类中有min和max方法。

So you can simply use:

所以你可以简单地使用:

Chars.min(myarray)

No conversions are required and presumably it's efficiently implemented.

不需要转换,而且可能是高效实现的。

#3


38  

You can simply use the new Java 8 Streams but you have to work with int.

您可以简单地使用新的Java 8流,但是您必须使用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,...

实用程序类数组的流方法为您提供了一个可以使用min方法的IntStream。你也可以做max, sum, average,…

The getAsInt method is used to get the value from the OptionalInt

getAsInt方法用于从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.

这种方法可以比经典循环提供更好的性能,因为汇总统计方法是一种简化操作,它允许并行化。

#4


19  

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


16  

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

  }

}

#6


9  

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

#7


2  

Here's a utility class providing min/max methods for primitive types: Primitives.java

这里有一个实用程序类,它为基本类型提供了min/max方法:原始类型。java。

#8


2  

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

#9


2  

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

将数组传递给一个用Arrays.sort()排序的方法,因此它只对方法使用的数组进行排序,然后将最小值设置为数组[0]和最大数组[array.length-1]。

#10


2  

You could easily do it with an IntStream and the max() method.

您可以轻松地使用IntStream和max()方法完成它。

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.

    范围(0,intArray.length) -获取一个包含在intArray中包含的元素的流。

  2. map(i -> intArray[i]) - Map every element of the stream to an actual element of the intArray.

    map(i -> intArray[i]) -将流的每个元素映射到intArray的实际元素。

  3. max() - Get the maximum element of this stream as OptionalInt.

    max() -将此流的最大元素作为OptionalInt。

  4. getAsInt() - Unwrap the OptionalInt. (You could also use here: orElse(0), just in case the OptionalInt is empty.)

    getAsInt() -打开OptionalInt。(你也可以在这里使用:orElse(0),以防OptionalInt是空的。)

#11


1  

Example with float:

示例与浮动:

public static float getMaxFloat(float[] data) {

    float[] copy = Arrays.copyOf(data, data.length);
    Arrays.sort(copy);
    return copy[data.length - 1];
}

public static float getMinFloat(float[] data) {

    float[] copy = Arrays.copyOf(data, data.length);
    Arrays.sort(copy);
    return copy[0];
}

#12


0  

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

#13


0  

public static <T> T getMax(T[] data) {
    T[] copy = Arrays.copyOf(data, data.length);
    Arrays.sort(copy);
    return copy[data.length - 1];
}

public static <T> T getMin(T[] data) {
    T[] copy = Arrays.copyOf(data, data.length);
    Arrays.sort(copy);
    return copy[0];
}

** be aware of possible null passed args :) (see handle null)

**注意可能通过的空值:)(参见处理null)

*** for primitive replace T with desired Type or use Arrays.asList()

***用于原始的替换T和所需的类型或使用Arrays.asList()

#14


0  

    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


134  

Using Commons Lang (to convert) + Collections (to min/max)

使用Commons Lang(转换)+集合(到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.

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

#2


53  

The Google Guava library has min and max methods in its Chars, Ints, Longs, etc. classes.

谷歌Guava库在其Chars、Ints、Longs等类中有min和max方法。

So you can simply use:

所以你可以简单地使用:

Chars.min(myarray)

No conversions are required and presumably it's efficiently implemented.

不需要转换,而且可能是高效实现的。

#3


38  

You can simply use the new Java 8 Streams but you have to work with int.

您可以简单地使用新的Java 8流,但是您必须使用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,...

实用程序类数组的流方法为您提供了一个可以使用min方法的IntStream。你也可以做max, sum, average,…

The getAsInt method is used to get the value from the OptionalInt

getAsInt方法用于从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.

这种方法可以比经典循环提供更好的性能,因为汇总统计方法是一种简化操作,它允许并行化。

#4


19  

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


16  

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

  }

}

#6


9  

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

#7


2  

Here's a utility class providing min/max methods for primitive types: Primitives.java

这里有一个实用程序类,它为基本类型提供了min/max方法:原始类型。java。

#8


2  

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

#9


2  

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

将数组传递给一个用Arrays.sort()排序的方法,因此它只对方法使用的数组进行排序,然后将最小值设置为数组[0]和最大数组[array.length-1]。

#10


2  

You could easily do it with an IntStream and the max() method.

您可以轻松地使用IntStream和max()方法完成它。

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.

    范围(0,intArray.length) -获取一个包含在intArray中包含的元素的流。

  2. map(i -> intArray[i]) - Map every element of the stream to an actual element of the intArray.

    map(i -> intArray[i]) -将流的每个元素映射到intArray的实际元素。

  3. max() - Get the maximum element of this stream as OptionalInt.

    max() -将此流的最大元素作为OptionalInt。

  4. getAsInt() - Unwrap the OptionalInt. (You could also use here: orElse(0), just in case the OptionalInt is empty.)

    getAsInt() -打开OptionalInt。(你也可以在这里使用:orElse(0),以防OptionalInt是空的。)

#11


1  

Example with float:

示例与浮动:

public static float getMaxFloat(float[] data) {

    float[] copy = Arrays.copyOf(data, data.length);
    Arrays.sort(copy);
    return copy[data.length - 1];
}

public static float getMinFloat(float[] data) {

    float[] copy = Arrays.copyOf(data, data.length);
    Arrays.sort(copy);
    return copy[0];
}

#12


0  

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

#13


0  

public static <T> T getMax(T[] data) {
    T[] copy = Arrays.copyOf(data, data.length);
    Arrays.sort(copy);
    return copy[data.length - 1];
}

public static <T> T getMin(T[] data) {
    T[] copy = Arrays.copyOf(data, data.length);
    Arrays.sort(copy);
    return copy[0];
}

** be aware of possible null passed args :) (see handle null)

**注意可能通过的空值:)(参见处理null)

*** for primitive replace T with desired Type or use Arrays.asList()

***用于原始的替换T和所需的类型或使用Arrays.asList()

#14


0  

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