四大函数式接口

函数型接口(function)

作用:传入什么,就输出什么
源码

@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}

使用

package com.luoKing.funcation;
import java.util.function.Function;
public class function {
public static void main(String[] args) {
// Function<String,String> function = new Function<String, String>() {
// @Override
// public String apply(String s) {
// return s;
// }
// };
Function<String,String> function = (str)->{
return str;
};
System.out.println(function.apply("asd"));
}
}

断点型接口

输入类型可以自定义,输出类型只能为boolon
源码

@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);

测试

package com.luoKing.funcation;
import java.util.function.Predicate;
public class predicae {
public static void main(String[] args) {
// Predicate<String> predicate = new Predicate<String>() {
// @Override
// public boolean test(String s) {
// return s.isEmpty();//判断字符串是否为空
// }
// };
Predicate<String> predicate = (str)->{
return str.isEmpty();
};
System.out.println(predicate.test("qwe"));
}
}

消费型接口(consumer)

作用:只接受参数,不返回参数
源码

@FunctionalInterface
public interface Consumer<T> {
void accept(T t);

实列

package com.luoKing.funcation;
import java.util.function.Consumer;
public class consumer {
public static void main(String[] args) {
// Consumer<String> consumer = new Consumer<String>() {
// @Override
// public void accept(String s) {
// System.out.println("hello,🙅‍");
// }
// };
Consumer<String> consumer = (String s)->{ System.out.println("hello,🙅‍");};
consumer.accept("sdadsasd");
}
}

供给者接口

不输入参数,只输出参数
源码

@FunctionalInterface
public interface Supplier<T> {
T get();
}

实例

package com.luoKing.funcation;
import java.util.function.Supplier;
public class supplier {
public static void main(String[] args) {
// Supplier<String> supplier = new Supplier<>() {
// @Override
// public String get() {
// return "hello,🙅‍";
// }
// };
Supplier<String> supplier = ()->{return "hello,🙅‍";};
System.out.println(supplier.get());
}
}

为什么要使用这四大函数式接口?

  1. 简化编程模型
  2. 在新版本的底层中大量应用
posted @   小罗要有出息  阅读(48)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示