java 中 尋找一個數組中的最大值或最小,除了自己專門編寫一個 min 或 max 函數外,還有幾種方式方便使用。
使用 stream
將一個數組放進 stream 里面,然后直接調用 stream 里的 min 或 max 函數得到最大值或最小值。
使用 collection
將數組轉化為對象數組,即 int 轉化為 Integer (需要使用 toObject 轉換)。 然后調用 Collection 里面的 min或max.
使用 Arrays 中的 sort
Arrays 類中的 sort 可以自動將一個數組排序,排序后數組中第一個元素就是 最小值,缺點是會改變數組。
————————————————
import java.util.Arrays;
import java.util.Collections;
import org.apache.commons.lang3.ArrayUtils;
public class HelloWorld {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[] = {10, 5, 8};
int min = Arrays.stream(a).min().getAsInt();
System.out.println(min);
min = Collections.min(Arrays.asList(ArrayUtils.toObject(a)));
System.out.println(min);
Arrays.sort(a);
System.out.println(a[0]);
}
}
