使用 Java 在原语数组中查找最大值/最小值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1484347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:19:51  来源:igfitidea点击:

Finding the max/min value in an array of primitives using Java

javaarraysalgorithmframeworks

提问by Nick Heiner

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

但这不是已经在某处完成了吗?

采纳答案by Michael Rutherfurd

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

使用 Commons Lang(转换)+ Collections(最小/最大)

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()包装底层数组,因此它不应占用太多内存,也不应在数组元素上执行复制。

回答by Bart Kiers

Yes, it's done in the Collectionsclass. Note that you will need to convert your primitive char array to a Character[] manually.

是的,它是在Collections类中完成的。请注意,您需要手动将原始字符数组转换为 Character[]。

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

回答by Christoph

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

这是一个提供min/max基本类型方法的实用程序类:Primitives.java

回答by Andrew McKinlay

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

谷歌番石榴库有最大值和最小值的方法在它的字符数,类型int,long等类。

So you can simply use:

所以你可以简单地使用:

Chars.min(myarray)

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

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

回答by mark2

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

回答by whoduexpect

Pass the array to a method that sorts it with Arrays.sort()so it only sorts the array the method is using then sets minto array[0]and maxto array[array.length-1].

将数组传递给对其进行排序的方法,Arrays.sort()以便它仅对方法正在使用的数组进行排序,然后将min设置为array[0]maxarray[array.length-1]

回答by Lubna_Nsour

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

  }

}

回答by Ortomala Lokni

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

你可以简单地使用新的Java 8Stream小号,但你必须有工作int

The streammethod of the utility class Arraysgives you an IntStreamon which you can use the minmethod. You can also do max, sum, average,...

stream实用程序类的方法Arrays为您提供了IntStream可以使用该min方法的方法。你也可以做max, sum, average, ...

The getAsIntmethod 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

如果执行时间很重要并且您只想浏览一次数据,则可以使用这样的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);
    }
}

This approach can give better performance than classical loop because the summaryStatisticsmethod is a reduction operationand it allows parallelization.

这种方法可以提供比经典循环更好的性能,因为该summaryStatistics方法是一种归约操作,并且允许并行化。

回答by Kim G.

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

回答by winklerrr

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

您可以使用 anIntStreammax()方法轻松完成。

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.

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

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

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

  1. range(0, intArray.length)- 获取包含与intArray.

  2. map(i -> intArray[i])- 将流的每个元素映射到intArray.

  3. max()- 获取此流的最大元素为OptionalInt

  4. getAsInt()- 解开OptionalInt. (您也可以在这里使用: orElse(0),以防万一OptionalInt为空。)