array find min in java code example
Example 1: find min in array java
private static int findMin(int[] array) {
int min = array[0];
for(int i=1;i<array.length;i++) {
if(min > array[i]) {
min = array[i];
}
}
return min;
}
Example 2: 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();
}
}
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);
}
}
Example 3: min array number in java
Integer[] num = { 2, 4, 7, 5, 9 };
int min1 = Collections.min(Arrays.asList(num));
int max1 = Collections.max(Arrays.asList(num));
System.out.println(min1);
System.out.println(max1);