赞
踩
如果一个接口只有一个抽象方法,那么该接口就是一个函数式接口
函数式接口的实例可以通过 lambda 表达式、方法引用或者构造方法引用来创建。
如果我们在某个接口上声明了 @FunctionalInterface 注解,那么编译器就会按照函数式接口的定义来要求该接口
如果某个接口只有一个抽象方法,但我们并没有给该接口声明 @FunctionalInterface 注解,那么编译器依旧会将该接口看作是函数式接口
1:四大函数式接口:Consumer、Supplier、Function、Predicate
开源码知道传入参数和返回类型 传入什么返回什么。
用匿名内部类new出函数式接口实现
lambda表达式简化
Predicate 传入泛型返回boolean类型
断定形接口
消费者接口
只有输入没有返回值
供给形接口
没有参数只有返回值
返回值类型为泛型。
- @FunctionalInterface
- public interface Consumer<T> {
-
- /**
- * Performs this operation on the given argument.
- *
- * @param t the input argument
- */
- void accept(T t);
- }
- package com.example.demo.java8;
-
- import java.util.function.Consumer;
-
- public class Java8InnerFunction {
-
- public static void main(String[] args) {
- Java8InnerFunction function=new Java8InnerFunction();
- function.consumMoney(1000,x-> System.out.println("消费了:"+x+"元"));
- }
-
- public void consumMoney(int money, Consumer consumer){
- consumer.accept(money);
- }
- }
- @FunctionalInterface
- public interface Supplier<T> {
-
- /**
- * Gets a result.
- *
- * @return a result
- */
- T get();
- }
- public static void main(String[] args) {
- Java8InnerFunction function=new Java8InnerFunction();
- int i = function.supplyRandomNum(() ->
- (int) (Math.random() * 100);
- );
- System.out.println("获得的随机数是:"+i);
- }
-
- public int supplyRandomNum(Supplier<Integer> supplier){
- return supplier.get();
- }
- @FunctionalInterface
- public interface Function<T, R> {
-
- /**
- * Applies this function to the given argument.
- *
- * @param t the function argument
- * @return the function result
- */
- R apply(T t);
- }
例子:计算一个数的10倍,并输出结果
- package com.example.demo.java8;
-
- import java.util.Random;
- import java.util.function.Consumer;
- import java.util.function.Function;
- import java.util.function.Supplier;
-
- public class Java8InnerFunction {
-
- public static void main(String[] args) {
- Java8InnerFunction function=new Java8InnerFunction();
-
- int i1 = function.functionCompute(5, x -> x * 10);
- System.out.println("计算后的结果值是:"+i1);
- }
-
- public int functionCompute(int a,Function<Integer,Integer> function){
- return function.apply(a);
- }
- }

- @FunctionalInterface
- public interface Predicate<T> {
-
- /**
- * Evaluates this predicate on the given argument.
- *
- * @param t the input argument
- * @return {@code true} if the input argument matches the predicate,
- * otherwise {@code false}
- */
- boolean test(T t);
- }
例子:计算一个数是否比100大,并输出真假
- public static void main(String[] args) {
- Java8InnerFunction function=new Java8InnerFunction();
-
- boolean b = function.predicateCompare(101, x -> x > 100);
- System.out.println("101比100大吗:"+b);
- }
-
-
- public boolean predicateCompare(int x,Predicate<Integer> predicate){
- return predicate.filter(x);
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。