JAVA四大內置函數


/**
* Consumer<T> : 消費型接口
* void accept(T t);
*
* Supplier<T> : 供給型接口
* T get();
*
* Function<T, R> : 函數型接口
* R apply(T t);
*
* Predicate<T> : 斷言型接口
* boolean test(T t);
*
*
*/

    @Test
    public void test1() {
        happy(10000,x -> System.out.println("喜歡大保健,每次消費"+ x));
        happy(10000,x -> {
            double a = x*100;
        });
    }

    public void happy(double money, Consumer<Double> con) {
        con.accept(money);
    }

test1結果:

 


 

//Supplier<T> 供給型接口:
    @Test
    public void test2(){ List<Integer> numList = getNumList(10,() -> (int)(Math.random()*100)); for(Integer num : numList) { System.out.println(num); } } //需求:產生指定個數的整數,並放入集合中 public List<Integer> getNumList(int num, Supplier<Integer> sup) { List<Integer> list = new ArrayList<>(); for(int i = 0; i < num ; i++) { Integer n = sup.get(); list.add(n); } return list; }

 test2結果:

 


 

 

//Function<T, R> 函數式接口
    @Test
    public void test3() { Integer num = strHandler("123",(x) -> Integer.valueOf(x) +10000); System.out.println(num); } //用於處理字符串 public Integer strHandler(String str, Function<String,Integer> fun) { return fun.apply(str); }

 test3結果:

 


 

//Predicate<T> 斷言型接口
    @Test
    public void test4() { List<String> list = Arrays.asList("helloww","www","abcdefg","ss","youyiku"); List<String> strings = filterStr(list, (x) -> x.length() > 3); for(String s: strings) { System.out.println(s); } } //需求,將滿足條件的字符串,放入集合中 public List<String> filterStr(List<String> list, Predicate<String> pre) { List<String> strList = new ArrayList<>(); for(String str: list) { if(pre.test(str)) { strList.add(str); } } return strList; }

 test 4結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM