java 8引入了lambda表达式,lambda表达式实际上表示的就是一个匿名的function。

在java 8之前,如果需要使用到匿名function需要new一个类的实现,但是有了lambda表达式之后,一切都变的非常简介。

我们看一个之前讲线程池的时候的一个例子:

//ExecutorService using class

ExecutorService executorService = Executors.newSingleThreadExecutor();

executorService.submit(new Runnable() {

@Override

public void run() {

log.info("new runnable");

}

});

executorService.submit需要接收一个Runnable类,上面的例子中我们new了一个Runnable类,并实现了它的run()方法。

上面的例子如果用lambda表达式来重写,则如下所示:

//ExecutorService using lambda

executorService.submit(()->log.info("new runnable"));

看起是不是很简单,使用lambda表达式就可以省略匿名类的构造,并且可读性更强。

那么是不是所有的匿名类都可以用lambda表达式来重构呢?也不是。

我们看下Runnable类有什么特点:

@FunctionalInterface

public interface Runnable

Runnable类上面有一个@FunctionalInterface注解。这个注解就是我们今天要讲到的Functional Interface。

Functional Interface

Functional Interface是指带有@FunctionalInterface注解的interface。它的特点是其中只有一个子类必须要实现的abstract方法。如果abstract方法前面带有default关键字,则不做计算。

其实这个也很好理解,因为Functional Interface改写成为lambda表达式之后,并没有指定实现的哪个方法,如果有多个方法需要实现的话,就会有问题。

@Documented

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.TYPE)

public @interface FunctionalInterface {}

Functional Interface一般都在java.util.function包中。

根据要实现的方法参数和返回值的不同,Functional Interface可以分为很多种,下面我们分别来介绍。

Function:一个参数一个返回值

Function接口定义了一个方法,接收一个参数,返回一个参数。

@FunctionalInterface

public interface Function {

/**

* Applies this function to the given argument.

*

* @param t the function argument

* @return the function result

*/

R apply(T t);

一般我们在对集合类进行处理的时候,会用到Function。

Map nameMap = new HashMap<>();

Integer value = nameMap.computeIfAbsent("name", s -> s.length());

上面的例子中我们调用了map的computeIfAbsent方法,传入一个Function。

上面的例子还可以改写成更短的:

Integer value1 = nameMap.computeIfAbsent("name", String::length);

Function没有指明参数和返回值的类型,如果需要传入特定的参数,则可以使用IntFunction, LongFunction, DoubleFunction:

@FunctionalInterface

public interface IntFunction {

/**

* Applies this function to the given argument.

*

* @param value the function argument

* @return the function result

*/

R apply(int value);

}

如果需要返回特定的参数,则可以使用ToIntFunction, ToLongFunction, ToDoubleFunction:

@FunctionalInterface

public interface ToDoubleFunction {

/**

* Applies this function to the given argument.

*

* @param value the function argument

* @return the function result

*/

double applyAsDouble(T value);

}

如果要同时指定参数和返回值,则可以使用DoubleToIntFunction, DoubleToLongFunction, IntToDoubleFunction, IntToLongFunction, LongToIntFunction, LongToDoubleFunction:

@FunctionalInterface

public interface LongToIntFunction {

/**

* Applies this function to the given argument.

*

* @param value the function argument

* @return the function result

*/

int applyAsInt(long value);

}

BiFunction:接收两个参数,一个返回值

如果需要接受两个参数,一个返回值的话,可以使用BiFunction:BiFunction, ToDoubleBiFunction, ToIntBiFunction, ToLongBiFunction等。

@FunctionalInterface

public interface BiFunction {

/**

* Applies this function to the given arguments.

*

* @param t the first function argument

* @param u the second function argument

* @return the function result

*/

R apply(T t, U u);

我们看一个BiFunction的例子:

//BiFunction

Map salaries = new HashMap<>();

salaries.put("alice", 100);

salaries.put("jack", 200);

salaries.put("mark", 300);

salaries.replaceAll((name, oldValue) ->

name.equals("alice") ? oldValue : oldValue + 200);

Supplier:无参的Function

如果什么参数都不需要,则可以使用Supplier:

@FunctionalInterface

public interface Supplier {

/**

* Gets a result.

*

* @return a result

*/

T get();

}

Consumer:接收一个参数,不返回值

Consumer接收一个参数,但是不返回任何值,我们看下Consumer的定义:

@FunctionalInterface

public interface Consumer {

/**

* Performs this operation on the given argument.

*

* @param t the input argument

*/

void accept(T t);

看一个Consumer的具体应用:

//Consumer

nameMap.forEach((name, age) -> System.out.println(name + " is " + age + " years old"));

Predicate:接收一个参数,返回boolean

Predicate接收一个参数,返回boolean值:

@FunctionalInterface

public interface Predicate {

/**

* 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);

如果用在集合类的过滤上面那是极好的:

//Predicate

List names = Arrays.asList("A", "B", "C", "D", "E");

List namesWithA = names.stream()

.filter(name -> name.startsWith("A"))

.collect(Collectors.toList());

Operator:接收和返回同样的类型

Operator接收和返回同样的类型,有很多种Operator:UnaryOperator BinaryOperator ,DoubleUnaryOperator, IntUnaryOperator, LongUnaryOperator, DoubleBinaryOperator, IntBinaryOperator, LongBinaryOperator等。

@FunctionalInterface

public interface IntUnaryOperator {

/**

* Applies this operator to the given operand.

*

* @param operand the operand

* @return the operator result

*/

int applyAsInt(int operand);

我们看一个BinaryOperator的例子:

//Operator

List values = Arrays.asList(1, 2, 3, 4, 5);

int sum = values.stream()

.reduce(0, (i1, i2) -> i1 + i2);

Functional Interface是一个非常有用的新特性,希望大家能够掌握。

本文的例子:https://github.com/ddean2009/learn-java-streams/tree/master/functional-interface

总结

到此这篇关于java中functional interface的分类和使用详解的文章就介绍到这了,更多相关java中functional interface的分类和使用内容请搜索云海天教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持云海天教程!

functional java_java中functional interface的分类和使用详解相关推荐

  1. dateformat java_java中Dateformat类的详细使用(详解)

    DateFormat其本身是一个抽象类,SimpleDateFormat 类是DateFormat类的子类,一般情况下来讲DateFormat类很少会直接使用,而都使用SimpleDateFormat ...

  2. python爬取图片-Python爬取网页中的图片(搜狗图片)详解

    前言 最近几天,研究了一下一直很好奇的爬虫算法.这里写一下最近几天的点点心得.下面进入正文: 你可能需要的工作环境: Python 3.6官网下载 本地下载 我们这里以sogou作为爬取的对象. 首先 ...

  3. 【C++】C++中的头文件(.h)—详解(1)

    [fishing-pan:https://blog.csdn.net/u013921430转载请注明出处] 前言 之前写过一篇<C++中头文件的使用>,那篇文章主要讲述C++中头文件的使用 ...

  4. colsure php_PHP_PHP中Closure类的使用方法及详解,Closure,匿名函数,又称为Anonym - phpStudy...

    PHP中Closure类的使用方法及详解 Closure,匿名函数,又称为Anonymous functions,是php5.3的时候引入的.匿名函数就是没有定义名字的函数.这点牢牢记住就能理解匿名函 ...

  5. Photoshop CS 中的“照片滤镜/Photo Filter”命令详解(转)

    Photoshop CS 中的"照片滤镜/Photo Filter"命令详解(转)[@more@] 这是一个跟摄影有关的重要图像调整命令. 有关这一命令的教程,现在网上没一个能说得 ...

  6. IP地址分类及范围详解

    IP地址分为公网IP地址(合法IP地址)和私有IP地址 公网IP地址主要应用于Internet上的主机访问,而私有IP地址应用于局域网中计算机的相互通信. IP地址的表示形式:分为二进制表示和点分十进 ...

  7. 【整理】串口(RS232/RS485等)通讯中RTS/CTS,DTR/DSR的含义详解

    [整理]串口(RS232/RS485等)通讯中RTS/CTS,DTR/DSR的含义详解 RS232 crifan 7年前 (2013-10-17) 14942浏览 0评论 [背景] 之前就折腾过很多关 ...

  8. oracle中的exists 和 not exists 用法详解

    from:http://blog.sina.com.cn/s/blog_601d1ce30100cyrb.html oracle中的exists 和 not exists 用法详解 (2009-05- ...

  9. R语言中如何计算C-Statistics?几种计算方法详解

    R语言中如何计算C-Statistics?几种计算方法详解 目录 R语言中如何计算C-Statistics? #包导入 #数据加载编码

最新文章

  1. 使用pandas correlation函数批量删除相关性冗余特征、实现特征筛选(feature selection)
  2. [译] 解密 Airbnb 的数据科学部门如何构建知识仓库
  3. python自学教材-python零基础自学教材
  4. 用python的五种方式_Python模块重载的五种方法
  5. 【Python基础入门系列】第08天:Python List
  6. python将元祖设为整形_python基础(5)---整型、字符串、列表、元组、字典内置方法和文件操作介绍...
  7. 首发骁龙665 小米CC9e 4+128G版到手价1199元
  8. Linux工作笔记037---Centos8.2下安装mysql_测试通过_注意这里安装8.0.22版本的_8.0以后的版本有需要注意的地方_跟7.0之前的版本不一样
  9. Zuul异常Zuul spring cloud zuul com.netflix.zuul.exception.ZuulException GENERAL
  10. iOS开发的架构模式
  11. Codeforces Round #162 (Div. 2): D. Good Sequences(DP)
  12. VMware虚拟机下载及安装教程
  13. sqlite内存模式
  14. java雷霆战机图片_JAVA开发《雷霆战机》雷电类游戏效果演示
  15. Unity新手开发VR项目
  16. 模块化 AMD与CMD 规范
  17. 为第九大股东;此前40次增持民生银行A股股份
  18. 全球及中国散热产业竞争现状与市场价值分析报告2022版
  19. Java中的所有关键
  20. 电脑搜索不到部分wifi,搜索不到部分2.4G频率的wif,手机开热点电脑搜不到wifi。

热门文章

  1. 打印店A4纸彩印多少钱一张?
  2. 每日学术速递3.27
  3. 太空射击第11课: Sound and Music
  4. 如何通过origin压缩进行压缩图片
  5. 10A10-ASEMI整流二极管10A10
  6. python operator 多属性排序_Python之路200个小例子网页版,真诚奉献,从一而终!...
  7. java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonMerge
  8. android UiAutomator写一个QQ小号给大号点赞的case
  9. 第九届全国大学生GIS应用技能大赛(A上午)
  10. GitHub 3.1K,业界首个流式语音合成系统开源