常用的函數式接口_Supplier接口練習_求數組元素最大值

求數組元素最大值

題目

使用Supplier 接口作爲方法參數類型,通過Lambda表達式求出int數組中的最大值。提示:接口的泛型請使用java.lang.Integer 類。

解答

package com.learn.demo04.Supplier;


import java.util.function.Supplier;

/*
    練習:求數組元素最大值
        使用Supplier接口作爲方法參數類型,通過Lambda表達式求出int數組中的最大值。
        提示:接口的泛型請使用java.lang.Integer類。
 */
public class Demo02Test {
   //定義一個方法,用於獲取int類型數組中元素的最大值,方法的參數傳遞Supplier接口,泛型使用Integer
   public static int getMax(Supplier<Integer> sup){
       return sup.get();
   }

    public static void main(String[] args) {
        //定義一個int類型的數組,並賦值
        int[] arr = {100,0,-50,880,99,33,-30};
        //調用getMax方法,方法的參數Supplier是一個函數式接口,所以可以傳遞Lambda表達式
        int maxValue = getMax(()->{
            //獲取數組的最大值,並返回
            //定義一個變量,把數組中的第一個元素賦值給該變量,記錄數組中元素的最大值
            int max = arr[0];
            //遍歷數組,獲取數組中的其他元素
            for (int i : arr) {
                //使用其他的元素和最大值比較
                if(i>max){
                    //如果i大於max,則替換max作爲最大值
                    max = i;
                }
            }
            //返回最大值
            return max;
        });
        System.out.println("數組中元素的最大值是:"+maxValue);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章