1. 使用 stream
將一個數組放進 stream 里面,然后直接調用 stream 里的 min 或 max 函數得到最大值。
@Test public void index2(){ int ages[] = {18 ,23 ,21 ,19 ,25 ,29 ,17}; int maxNum = Arrays.stream(ages).max().getAsInt(); System.out.println("最大值為:"+ maxNum); }
2. 使用 collection
將數組轉化為對象數組,即 int 轉化為 Integer (需要使用數組轉換)。 然后調用 Collection 里面的 min或max.
@Test public void index3(){ int ages[] = {18 ,23 ,21 ,19 ,25 ,29 ,17}; Integer newAges[] = new Integer[ages.length]; for(int i=0;i<ages.length;i++) { newAges[i] = (Integer)ages[i]; } int maxNum = Collections.max(Arrays.asList(newAges)); System.out.println("最大值為:"+ maxNum); }
3. 使用 Arrays 中的 sort
Arrays 類中的 sort 可以自動將一個數組排序,排序后數組中最后一個元素就是 最大值,缺點是會改變數組。
@Test public void index1(){ int ages[] = {18 ,23 ,21 ,19 ,25 ,29 ,17}; Arrays.sort(ages); int maxNum = ages[ages.length-1]; System.out.println("最大值為:"+ maxNum); }
4.使用自定義函數
默認把第一個元素作為最大值,然后for循環,如果大於最大值,則進行替換。
public int getMaxAge() { int ages[] = {18 ,23 ,21 ,19 ,25 ,29 ,17}; int max = ages[0]; for(int i = 1;i<ages.length;i++){ if(ages[i]>max){ max = ages[i]; } } return max; }