max of int array code example

Example 1: how to get the max value of an array java

public static double arrayMax(double[] arr) {
    double max = Double.NEGATIVE_INFINITY;

    for(double cur: arr)
        max = Math.max(max, cur);

    return max;
}

Example 2: find the maximum number from an int Array

---without sort method---
public static int maxValue( int[]  n ) {

int max = Integer.MIN_VALUE;

for(int each: n)

if(each > max)

max = each;

 
return max;
  
---with sort method---
public static int maxValue( int[]  n ) {

Arrays.sort( n );

return  n [ n.lenth-1 ];

}

Example 3: java 8 find min value in array

package com.concerned.crossbill;

import java.util.Arrays;

public class Foo {

  public int getMin(int[] numbers) {
	return Arrays.stream(numbers).min().getAsInt();
  }
}
// test class
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import com.concerned.crossbill.Foo;

public class FooTest { 
  public void testGetMin() {
    int[] numbers =  new int[]{12, 10, 31, 30, 23, 4, 5, 5, 5, 5, 10, 40};
    
    Foo foo = new Foo();
    int result  = foo.getMin(numbers);
    int expResult  = 4;
    
    assertEquals(expResult, result);
  }
}

Tags:

Misc Example