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

前端 未结 15 2063
遥遥无期
遥遥无期 2020-11-22 05:09

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         


        
15条回答
  •  执念已碎
    2020-11-22 05:23

    You can simply use the new Java 8 Streams but you have to work with 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,...

    The getAsInt method is used to get the value from the 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.

提交回复
热议问题