lambda 에 대한 노트

3460 단어 Java
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);
    }
}

좋은 웹페이지 즐겨찾기