未公开接口主要指以下哪几类_Java8的 Stream 函数式接口,你了解多少?
点击蓝色“程序职场”关注我哟
加个“星标”,天天和你一起进步
作者:litesky
www.jianshu.com/p/2338cabc59e1
函数式接口是伴随着Stream的诞生而出现的,Java8Stream 作为函数式编程的一种具体实现,开发者无需关注怎么做,只需知道要做什么,各种操作符配合简洁明了的函数式接口给开发者带来了简单快速处理数据的体验。
函数式接口
什么是函数式接口?简单来说就是只有一个抽象函数的接口。为了使得函数式接口的定义更加规范,java8 提供了@FunctionalInterface 注解告诉编译器在编译器去检查函数式接口的合法性,以便在编译器在编译出错时给出提示。为了更加规范定义函数接口,给出如下函数式接口定义规则:
有且仅有一个抽象函数
必须要有@FunctionalInterface 注解
可以有默认方法
可以看出函数式接口的编写定义非常简单,不知道大家有没有注意到,其实我们经常会用到函数式接口,如Runnable 接口,它就是一个函数式接口:
@FunctionalInterfacepublic interface Runnable { /** * When an object implementing interface Runnable
is used * to create a thread, starting the thread causes the object's * run
method to be called in that separately executing * thread. *
run is that it may
* The general contract of the method
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
过去我们会使用匿名内部类来实现线程的执行体:
new Thread(new Runnable() { @Overridepublic void run() { System.out.println("Hello FunctionalInterface"); } }).start();
现在我们使用Lambda 表达式,这里函数式接口的使用没有体现函数式编程思想,这里输出字符到标准输出流中,产生了副作用,起到了简化代码的作用,当然还有装B。
new Thread(()->{ System.out.println("Hello FunctionalInterface"); }).start();
Java8 util.function 包下自带了43个函数式接口,大体分为以下几类:
Consumer 消费接口
Function 功能接口
Operator 操作接口
Predicate 断言接口
Supplier 生产接口
其他接口都是在此基础上变形定制化罢了。
函数式接口详细介绍
这里只介绍最基础的函数式接口,至于它的变体只要明白了基础自然就能够明白。前篇:玩转Java8中的 Stream 之从零认识 Stream
Consumer
消费者接口,就是用来消费数据的。
@FunctionalInterfacepublic interface Consumer<T> {
/** * Performs this operation on the given argument. * * @param t the input argument */ void accept(T t);
/** * Returns a composed {@code Consumer} that performs, in sequence, this * operation followed by the {@code after} operation. If performing either * operation throws an exception, it is relayed to the caller of the * composed operation. If performing this operation throws an exception, * the {@code after} operation will not be performed. * * @param after the operation to perform after this operation * @return a composed {@code Consumer} that performs in sequence this * operation followed by the {@code after} operation * @throws NullPointerException if {@code after} is null */ default Consumer andThen(Consumer super T> after) { Objects.requireNonNull(after); return (T t) -> { accept(t); after.accept(t); }; }}
Consumer 接口中有accept 抽象方法,accept接受一个变量,也就是说你在使用这个函数式接口的时候,给你提供了数据,你只要接收使用就可以了;andThen 是一个默认方法,接受一个Consumer 类型,当你对一个数据使用一次还不够爽的时候,你还能再使用一次,当然你其实可以爽无数次,只要一直使用andThan方法。
Function
何为Function呢?比如电视机,给你带来精神上的愉悦,但是它需要用电啊,电视它把电转换成了你荷尔蒙,这就是Function,简单电说,Function 提供一种转换功能。
@FunctionalInterfacepublic interface Function<T, R> {
/** * Applies this function to the given argument. * * @param t the function argument * @return the function result */ R apply(T t);
/** * Returns a composed function that first applies the {@code before} * function to its input, and then applies this function to the result. * If evaluation of either function throws an exception, it is relayed to * the caller of the composed function. * * @param the type of input to the {@code before} function, and to the * composed function * @param before the function to apply before this function is applied * @return a composed function that first applies the {@code before} * function and then applies this function * @throws NullPointerException if before is null * * @see #andThen(Function) */ default Function<V, R> compose(Function super V, ? extends T> before) { Objects.requireNonNull(before);return (V v) -> apply(before.apply(v)); }/** * Returns a composed function that first applies this function to * its input, and then applies the {@code after} function to the result. * If evaluation of either function throws an exception, it is relayed to * the caller of the composed function. * * @param the type of output of the {@code after} function, and of the * composed function * @param after the function to apply after this function is applied * @return a composed function that first applies this function and then * applies the {@code after} function * @throws NullPointerException if after is null * * @see #compose(Function) */default Function<T, V> andThen(Function super R, ? extends V> after) { Objects.requireNonNull(after);return (T t) -> after.apply(apply(t)); }/** * Returns a function that always returns its input argument. * * @param the type of the input and output objects to the function * @return a function that always returns its input argument */static Function<T, T> identity() {return t -> t; }}
Function 接口 最主要的就是apply 函数,apply 接受T类型数据并返回R类型数据,就是将T类型的数据转换成R类型的数据,它还提供了compose、andThen、identity 三个默认方法,compose 接受一个Function,andThen也同样接受一个Function,这里的andThen 与Consumer 的andThen 类似,在apply之后在apply一遍,compose 则与之相反,在apply之前先apply(这两个apply具体处理内容一般是不同的),identity 起到了类似海关的作用,外国人想要运货进来,总得交点税吧,然后货物才能安全进入中国市场,当然了想不想收税还是你说了算的:。
Operator
可以简单理解成算术中的各种运算操作,当然不仅仅是运算这么简单,因为它只定义了运算这个定义,但至于运算成什么样你说了算。由于没有最基础的Operator,这里将通过 BinaryOperator、IntBinaryOperator来理解Operator 函数式接口,先从简单的IntBinaryOperator开始。
IntBinaryOperator
从名字可以知道,这是一个二元操作,并且是Int 类型的二元操作,那么这个接口可以做什么呢,除了加减乘除,还可以可以实现平方(两个相同int 数操作起来不就是平方吗),还是先看看它的定义吧:
@FunctionalInterfacepublic interface IntBinaryOperator {
/** * Applies this operator to the given operands. * * @param left the first operand * @param right the second operand * @return the operator result */ int applyAsInt(int left, int right);}
IntBinaryOperator 接口内只有一个applyAsInt 方法,其接收两个int 类型的参数,并返回一个int 类型的结果,其实这个跟Function 接口的apply 有点像,但是这里限定了,只能是int类型。
BinaryOperator
BinaryOperator 二元操作,看起来它和IntBinaryOperator 是父子关系,实际上这两者没有半点关系,但他们在功能上还是有相似之处的:
@FunctionalInterfacepublic interface BinaryOperator<T> extends BiFunction<T,T,T> { /** * Returns a {@link BinaryOperator} which returns the lesser of two elements * according to the specified {@code Comparator}. * * @param the type of the input arguments of the comparator * @param comparator a {@code Comparator} for comparing the two values * @return a {@code BinaryOperator} which returns the lesser of its operands, * according to the supplied {@code Comparator} * @throws NullPointerException if the argument is null */ public static BinaryOperator minBy(Comparator super T> comparator) { Objects.requireNonNull(comparator);return (a, b) -> comparator.compare(a, b) <= 0 ? a : b; }/** * Returns a {@link BinaryOperator} which returns the greater of two elements * according to the specified {@code Comparator}. * * @param the type of the input arguments of the comparator * @param comparator a {@code Comparator} for comparing the two values * @return a {@code BinaryOperator} which returns the greater of its operands, * according to the supplied {@code Comparator} * @throws NullPointerException if the argument is null */public static BinaryOperator maxBy(Comparator super T> comparator) { Objects.requireNonNull(comparator);return (a, b) -> comparator.compare(a, b) >= 0 ? a : b; }}
BinaryOperator 是 BiFunction 生的,而IntBinaryOperator 是从石头里蹦出来的,BinaryOperator 自身定义了minBy、maxBy默认方法,并且参数都是Comparator,就是根据传入的比较器的比较规则找出最小最大的数据。
Predicate
断言、判断,对输入的数据根据某种标准进行评判,最终返回boolean值:
@FunctionalInterfacepublic 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);
/** * Returns a composed predicate that represents a short-circuiting logical * AND of this predicate and another. When evaluating the composed * predicate, if this predicate is {@code false}, then the {@code other} * predicate is not evaluated. * *
Any exceptions thrown during evaluation of either predicate are relayed
* to the caller; if evaluation of this predicate throws an exception, the
* {@code other} predicate will not be evaluated.
*
* @param other a predicate that will be logically-ANDed with this
* predicate
* @return a composed predicate that represents the short-circuiting logical
* AND of this predicate and the {@code other} predicate
* @throws NullPointerException if other is null
*/
default Predicate and(Predicate super T> other) {
Objects.requireNonNull(other);return (t) -> test(t) && other.test(t);
}/**
* Returns a predicate that represents the logical negation of this
* predicate.
*
* @return a predicate that represents the logical negation of this
* predicate
*/default Predicate negate() {return (t) -> !test(t);
}/**
* Returns a composed predicate that represents a short-circuiting logical
* OR of this predicate and another. When evaluating the composed
* predicate, if this predicate is {@code true}, then the {@code other}
* predicate is not evaluated.
*
*
Any exceptions thrown during evaluation of either predicate are relayed
* to the caller; if evaluation of this predicate throws an exception, the
* {@code other} predicate will not be evaluated.
*
* @param other a predicate that will be logically-ORed with this
* predicate
* @return a composed predicate that represents the short-circuiting logical
* OR of this predicate and the {@code other} predicate
* @throws NullPointerException if other is null
*/
default Predicate or(Predicate super T> other) {
Objects.requireNonNull(other);return (t) -> test(t) || other.test(t);
}/**
* Returns a predicate that tests if two arguments are equal according
* to {@link Objects#equals(Object, Object)}.
*
* @param the type of arguments to the predicate
* @param targetRef the object reference with which to compare for equality,
* which may be {@code null}
* @return a predicate that tests if two arguments are equal according
* to {@link Objects#equals(Object, Object)}
*/static Predicate isEqual(Object targetRef) {return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
}
Predicate的test 接收T类型的数据,返回 boolean 类型,即对数据进行某种规则的评判,如果符合则返回true,否则返回false;Predicate接口还提供了 and、negate、or,与 取反 或等,isEqual 判断两个参数是否相等等默认函数。
Supplier
生产、提供数据:
@FunctionalInterfacepublic interface Supplier<T> {
/** * Gets a result. * * @return a result */ T get();}
非常easy,get方法返回一个T类数据,可以提供重复的数据,或者随机种子都可以,就这么简单。
函数式接口实战
Consumer
Consumer 用的太多了,不想说太多,如下:
public class Main { public static void main(String[] args) { Stream.of(1,2,3,4,5,6) .forEach(integer -> System.out.println(integer)); //输出1,2,3,4,5,6 }}
这里使用标准输出,还是产生了副作用,但是这种程度是可以允许的
Function
1.转换,将字符串转成长度
public class Main { public static void main(String[] args) { Stream.of("hello","FunctionalInterface") .map(e->e.length()) .forEach(System.out::println); }}
2.运算
public class FunctionTest {
public static void main(String[] args) {
public static void main(String[] args) {
Function<Integer, Integer> square = integer -> integer * integer; //定义平方运算
List list = new ArrayList<>();list.add(1);list.add(2);list.add(3);list.add(4);list.stream() .map(square.andThen(square)) //四次方 .forEach(System.out::println); System.out.println("------");list.stream() .map(square.compose(e -> e - 1)) //减一再平方 .forEach(System.out::println); System.out.println("------");list.stream().map(square.andThen(square.compose(e->e/2))) //先平方然后除2再平方 .forEach(System.out::println); }}
结果如图:
Operator
1.BinaryOperator
这里实现找最大值:
public class BinaryOperatorTest {
public static void main(String[] args) {
Stream.of(2,4,5,6,7,1) .reduce(BinaryOperator.maxBy(Comparator.comparingInt(Integer::intValue))).ifPresent(System.out::println);
}}
Comparator 后期会讲到
2.IntOperator
这里实现累加功能:
public class BinaryOperatorTest {
public static void main(String[] args) { IntBinaryOperator intBinaryOperator = (e1, e2)->e1+e2; //定义求和二元操作 IntStream.of(2,4,5,6,7,1) .reduce(intBinaryOperator).ifPresent(System.out::println); }}
Predicate
筛选出大于0最小的两个数
public class Main {
public static void main(String[] args) { IntStream.of(200,45,89,10,-200,78,94) .filter(e->e>0) //过滤小于0的数 .sorted() //自然顺序排序 .limit(2) //取前两个 .forEach(System.out::println); }}
Supplier
这里一直生产2这个数字,为了能停下来,使用limit
public class Main {
public static void main(String[] args) { Stream.generate(()->2) .limit(10) .forEach(System.out::println); }}
如图:
总结
Java8的Stream 基本上都是使用util.function包下的函数式接口来实现函数式编程的,而函数式接口也就只分为 Function、Operator、Consumer、Predicate、Supplier 这五大类,只要能理解掌握最基础的五大类用法,其他变种也能触类旁通。
最后祝看完这篇文章的小伙伴收获满满!点个在看吧~
▎好文推荐
点击☞职场我们如何寻找自己的定位(职场)
点击☞没有资源和运营能力,如何开启副业之路(副业)
点击☞项目中怎么使用敏捷开发流程(敏捷)
点击☞【程序职场】第一期学习资料(java)
▎我的开源项目
点击☞一点知识学院(Spring boot 开源项目)(技能)
点击☞一Eclipse项目如何导入IDEA正常启动(案例:一点知识学院)
快加微信(mmlz6879),回复「程序职场」或右下角点击「撩我 -> 加群」拉你进讨论群和众多爱学习的小伙伴一起学习。转发至朋友圈,是对我最大的支持。
未公开接口主要指以下哪几类_Java8的 Stream 函数式接口,你了解多少?相关推荐
- jdk8新特性(接口新特性、lambda表达式、方法引用、函数式接口、Stream流)和单例设计模式
1.单例设计模式 1.概念: 设计模式:使用固有的流程或方式设计出来的类接口.枚举等元素 2.设计原则: 1.私有化构造方法[private.protected] 2.类中创建最终对象[唯一不能被赋值 ...
- java新特性-函数式接口-作为方法参数-作为方法的返回值-常用函数式接口-Supplier-Consumer-Predicate-Function
文章目录 函数式接口 概念 函数式接口作为方法参数 函数式接口作为方法的返回值 常用函数式接口 Supplier接口 常用函数式接口 Consumer 函数式接口之 Predicate接口 常用接口之 ...
- Java8 Stream 函数式接口
在这里插入图片描述 先贴上几个案例,水平高超的同学可以挑战一下: 从员工集合中筛选出salary大于8000的员工,并放置到新的集合里. 统计员工的最高薪资.平均薪资.薪资之和. 将员工按薪资从高到低 ...
- java socket接口文档_Java进阶 - 网络编程、Socket、函数式接口、常用的函数式接口...
1.网络通信协议 网络通信协议:通信协议是对计算机必须遵守的规则,只有遵守这些规则,计算机之间才能进行通信.这就好比在道路中行驶的汽车一定要遵守交通规则一样,协议中对数据的传输格式.传输速率.传输步骤 ...
- java模拟使用接口,关于java:模拟一个类与模拟它的接口
对于单元测试,我需要模拟几个依赖项.依赖项之一是实现接口的类: public class DataAccessImpl implements DataAccess { ... } 我需要设置一个这个类 ...
- 十三、Java高级特性 Lambda表达式 | 接口组成更新 | 方法引用 | 函数式接口
文章目录 十三.Java高级特性 1.Lambda表达式 1.1体验Lambda表达式[理解] 1.2Lambda表达式的标准格式[理解] 1.3Lambda表达式练习1[应用] 1.4Lambda表 ...
- java函数式接口意义与场景
前言 想到记录下这篇主要是两个原因,1. 虽然自己很早就接触了函数式接口,但是基本没有深入探究过使用场景.2. 工作中接触了越来越多场景后,感觉对函数式接口有更多使用需求,能很好的美化自己代码(少写几 ...
- JAVA学习笔记 15 - 函数式接口、Lambda表达式和方法引用
本文是Java基础课程的第十五课.主要介绍在JDK8中,Java引入的部分新特性,包括函数式接口.Lambda表达式和方法引用.这些新特性使得Java能够在按照面向对象思想进行开发的基础上,融合函数式 ...
- 函数式接口、方法引用
概念 函数式接口在Java中是指:有且仅有一个抽象方法的接口. 函数式接口,即适用于函数式编程场景的接口.而Java中的函数式编程体现就是Lambda,所以函数式接口就是可以适用于Lambda使用的接 ...
最新文章
- Java split(“\\s+“) 和 split(“+“) 有什么区别
- 高速行车12条技巧,每一条都关乎你的生命
- leetcode刷题:搜索旋转排序数组
- WCF把书读薄(4)——事务编程与可靠会话
- Parallels Desktop 安装Win 10提示“安全启动功能防止操作系统启动”该如何操作?
- 阿里38号元老:管理要轻,文化要浓
- hsqldb mysql_HSQLDB的研究与性能测试(与Mysql对比)
- android+世界地图高清版大图片,世界地图全图高清版
- 【Python】torrentParser1.01
- 积分商城使用教程之优惠券
- PDF Expert教程|七个提高效率的小技巧
- win10系统许可证即将过期的解决方法
- c语言程序设计中国传媒大学,中国传媒大学82《程序设计》考试大纲.doc
- 【bug】vue.runtime.esm.js?2b0e:619 [Vue warn]: Failed to mount component: template or render function
- ClickHouce 常用字符串函数
- linux使用虚拟ip路由问题,linux – 来自主机的虚拟机的IPv6公共路由
- The system cannot find the path specified
- 想去阿里大厂去面试测试工程师?想月薪15k?这篇文章一定对你有所帮助
- vue—实现组织架构图(vue-org-tree插件)——技能提升
- vue后端返回数据流 前端导出下载xls文件
热门文章
- 干货!Elasticsearch性能优化实战指南
- go build -X 的妙用
- Go channel 的妙用
- Wave-Share -无服务器,点对点,通过声音共享本地文件
- LiveVideoStack线上分享第五季(一):企业视频会议场景下的流量分发和弱网优化...
- 鹅厂设计师是如何做设计的?
- Shell 变量--shell教程
- librtmp协议分析---RTMP_SendPacket函数
- AliSQL开源Sequence Engine
- leetcode 794. Valid Tic-Tac-Toe State | 794. 有效的井字游戏(Java)