2021-03-30四大java函数型接口

package text;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class Demo3 {
    public static void main(String[] args) {
        //匿名内部类consumer消费型接口
        Consumer consumer = new Consumer() {
            @Override
            public void accept(Double aDouble) {
                System.out.println("聚餐消费" + aDouble);
            }
        };
        //Lambda表达式
        Consumer consumer1 = (d) -> System.out.println("聚餐消费" + d);
        happy(consumer1, 5);

        //供给型接口
        int[] nums = getNums(() -> new Random().nextInt(100), 5);
        String nums1 = getNums1(() -> "halleo", 2);
        System.out.println(Arrays.toString(nums));
        System.out.println(nums1);
        String s1 = handlerString((s) -> s.toUpperCase(), "hello");
        System.out.println(s1);
        List names = new ArrayList<>();
        names.add("zhangs");
        names.add("lis");
        names.add("wangwu");
        names.add("zhaoliu");
        List list = filterNames(s -> s.startsWith("zhang"), names);
        System.out.println(list.toString());
    }

    public static void happy(Consumer consumer, double money) {
        consumer.accept(money);
    }

    //Supplier 供给型接口
    public static int[] getNums(Supplier supplier, int count) {
        int[] arr = new int[count];
        for (int i = 0; i < count; i++) {
            arr[i] = supplier.get();
        }
        return arr;
    }
    //Supplier 供给型接口
    public static String getNums1(Supplier supplier, int count) {
        String substring = supplier.get().substring(count);
        return substring;
    }
    //Function函数型接口
    public static String handlerString(Function function,String str){
       return function.apply(str);
    }
    //Predicate 断言型接口
    public static List filterNames(Predicate predicate,List list){
        List list1 =new ArrayList<>();
        for (String string : list){
            if (predicate.test(string)){
                list1.add(string);
            }
        }
        return list1;
    }
}

你可能感兴趣的:(2021-03-30四大java函数型接口)