java8新特性-Lambda内置四大核心函数式接口(3)

Java 8 内置四大核心函数式编程接口

   Consumer<T> 消费型接口
    void accept(T t);

   Supplier<T> 供给型接口
     T get();

   Function<T,R> 函数型接口
     R apply(T t);

   Predicate<T> 断言型接口
     boolean test(T t);

接下来是这四个函数式接口的使用

/**
 * Java 8 内置四大核心函数式编程接口
 * <p>
 * Consumer<T> 消费型接口
 * void accept(T t);
 * <p>
 * Supplier<T> 供给型接口
 * T get();
 * <p>
 * Function<T,R> 函数型接口
 * R apply(T t);
 * <p>
 * Predicate<T> 断言型接口
 * boolean test(T t);
 *
 * @author Administrator
 * @version 1.0
 * @date 2019/11/6 16:25
 */
public class Java8LambdaTestCase extends Java8LambdaApplicationTests {


    //Consumer
    @Test
    public void test() {
        play(1000, (x) -> System.out.println("小明消费了" + x + "元"));
    }

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

    //Supplier 需求:产出指定个数的随机数字,放入集合中
    @Test
    public void test1() {
        List<Integer> lists = getLists(10, () -> (int) (Math.random() * 100));
        lists.forEach(System.out::println);
    }

    public List<Integer> getLists(int num, Supplier<Integer> supplier) {
        List<Integer> list = new ArrayList<>(num);
        for (int i = 0; i < num; i++) {
            list.add(supplier.get());
        }
        return list;
    }

    //Function 函数式接口
    //需求 :把 adc 字符串转换成 大写字母
    @Test
    public void test2() {
        String abc = getUp("abc", x -> x.toUpperCase());
        System.out.println(abc);
    }

    public String getUp(String str, Function<String, String> function) {
        return function.apply(str);
    }


    //Predicate
    //从集合中查出字符长度大于3的数据
    @Test
    public void test3() {
        List<String> lists = Arrays.asList("adc", "adddd", "hgello word", "ok", "test");
        List<String> list = hasTest(lists, e -> e.length() > 3);
        list.forEach(System.out::println);
    }

    public List<String> hasTest(List<String> lists, Predicate<String> predicate) {
        List<String> list = new ArrayList<>();
        lists.forEach(each -> {
            if (predicate.test(each)) {
                list.add(each);
            }
        });
        return list;
    }


}
发布了256 篇原创文章 · 获赞 188 · 访问量 65万+

猜你喜欢

转载自blog.csdn.net/qq_40646143/article/details/102938295