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<T>
//定义一个消费者,要对某个对象做什么功能
Consumer <String> consumer = str -> System.out.println(str);
//消费者对具体的对象去执行它要做的功能
consumer.accept("aaaa");
ConsumerInterface consumerInterface = str -> System.out.println(str);
consumerInterface.consume("aaaaaaaaaaa");
//供给型接口Supplier<T>
//定义一个生产者,提供一个具体的对象
Supplier <String> supplier = () -> "cjx913";
System.out.println(supplier.get());
SupplierInterface supplierInterface = () -> "cjx913";
System.out.println(supplierInterface.supply());
//函数式接口Function<T,R>
//定义一个函数,T为参数类型,R为返回类型
//Integer转为String
Function <Integer, String> function = integer -> String.valueOf(integer);
System.out.println(function.apply(34));
//把返回的String类型的值转为Long类型
Function <Integer, Long> andThen = function.andThen(Long::valueOf);
System.out.println(andThen.apply(24));
//把返回的Long类型的值转为Double类型
Function <Integer, Double> then = andThen.andThen(Long::doubleValue);
System.out.println(then.apply(22));
//----------另一例子----------
Function <Double, Double> f = x -> x * 2.0 + 5.2;
Function <Double, Double> g = x -> (x + 5) * 2.4;
Function <Double, Double> t = x -> x * x - 3.1;
Function <Double, Double> result1 = f.andThen(g).andThen(t);
System.out.println("t(g(f(3.2)))=" + result1.apply(3.2));//t(g(f(3.2)))
Function <Double, Double> 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<T>
Predicate <String> predicate = str -> str.startsWith("a") ? true : false;
System.out.println(predicate.test("abcd"));
System.out.println(predicate.test("dcba"));
Predicate <String> and = predicate.and(str -> str.startsWith("d") ? true : false);
System.out.println(and.test("dcba"));//相当于两个断言的结果:predicate&&and
Predicate <String> 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);
}
}