关于lambda的一些笔记

package com.cjx913.lambda;

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class Main {

    public static void main(String[] args) {
        //消费型接口Consumer
        //定义一个消费者,要对某个对象做什么功能
        Consumer  consumer = str -> System.out.println(str);
        //消费者对具体的对象去执行它要做的功能
        consumer.accept("aaaa");

        ConsumerInterface consumerInterface = str -> System.out.println(str);
        consumerInterface.consume("aaaaaaaaaaa");

        //供给型接口Supplier
        //定义一个生产者,提供一个具体的对象
        Supplier  supplier = () -> "cjx913";
        System.out.println(supplier.get());

        SupplierInterface supplierInterface = () -> "cjx913";
        System.out.println(supplierInterface.supply());

        //函数式接口Function
        //定义一个函数,T为参数类型,R为返回类型
        //Integer转为String
        Function  function = integer -> String.valueOf(integer);
        System.out.println(function.apply(34));

        //把返回的String类型的值转为Long类型
        Function  andThen = function.andThen(Long::valueOf);
        System.out.println(andThen.apply(24));
        //把返回的Long类型的值转为Double类型
        Function  then = andThen.andThen(Long::doubleValue);
        System.out.println(then.apply(22));

        //----------另一例子----------
        Function  f = x -> x * 2.0 + 5.2;
        Function  g = x -> (x + 5) * 2.4;
        Function  t = x -> x * x - 3.1;
        Function  result1 = f.andThen(g).andThen(t);
        System.out.println("t(g(f(3.2)))=" + result1.apply(3.2));//t(g(f(3.2)))

        Function  result2 = f.compose(g).compose(t);
        System.out.println("f(g(t(3.2)))=" + result2.apply(3.2));//f(g(t(3.2)))

        FunctionInterface functionInterface = (integer) -> integer + "cjx913";
        System.out.println(functionInterface.apply(32));

        //断言型接口Predicate
        Predicate  predicate = str -> str.startsWith("a") ? true : false;
        System.out.println(predicate.test("abcd"));
        System.out.println(predicate.test("dcba"));

        Predicate  and = predicate.and(str -> str.startsWith("d") ? true : false);
        System.out.println(and.test("dcba"));//相当于两个断言的结果:predicate&&and

        Predicate  or = predicate.or(str -> str.startsWith("d") ? true : false);
        System.out.println(or.test("dcba"));//相当于两个断言的结果:predicate||or

        PredicateInterface predicateInterface = str -> str.startsWith("a") ? true : false;
        System.out.println(predicateInterface.test("abcd"));
        System.out.println(predicateInterface.test("dcba"));
    }

    public interface ConsumerInterface {
        void consume(String string);
    }

    public interface SupplierInterface {
        String supply();
    }

    public interface FunctionInterface {
        String apply(Integer integer);
    }

    public interface PredicateInterface {
        boolean test(String string);
    }
}

 

你可能感兴趣的:(Java)