Introduction to Functional Interfaces – A concept recreated in Java 8

Any java developer around the world would have used at least one of the following interfaces: java.lang.Runnable,java.awt.event.ActionListener, java.util.Comparator,java.util.concurrent.Callable. There is some common feature among the stated interfaces and that feature is they have only one method declared in their interface definition. There are lot more such interfaces in JDK and also lot more created by java developers. These interfaces are also called Single Abstract Method interfaces (SAM Interfaces). And a popular way in which these are used is by creating Anonymous Inner classes using these interfaces, something like:
[java]
public class AnonymousInnerClassTest {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Aad created and running …");
}
}).start();
}
}
[/java]

With Java 8 the same concept of SAM interfaces is recreated and are called Functional interfaces. These can be represented using Lambda expressions, Method reference and constructor references(I will cover these two topics in the upcoming blog posts). There’s an annotation introduced- @FunctionalInterface which can be used for compiler level errors when the interface you have annotated is not a valid Functional Interface. Lets try to have a look at a simple functional interface with only one abstract method:
[java]
@FunctionalInterface
public interface SimpleFuncInterface {
public void doWork();
}
[/java]
The interface can also declare the abstract methods from thejava.lang.Object class, but still the interface can be called as a Functional Interface:
[java]
@FunctionalInterface
public interface SimpleFuncInterface {
public void doWork();
public String toString();
public boolean equals(Object o);
}
[/java]
Once you add another abstract method to the interface then the compiler/IDE will flag it as an error as shown in the screenshot below:

Interface can extend another interface and in case the Interface it is extending in functional and it doesn’t declare any new abstract methods then the new interface is also functional. But an interface can have one abstract method and any number of default methods and the interface would still be called an functional interface. To get an idea of default methods please read here.
[java]
@FunctionalInterface
public interface ComplexFunctionalInterface extends SimpleFuncInterface {
default public void doSomeWork(){
System.out.println("Doing work in interface impl…");
}
default public void doSomeOtherWork(){
System.out.println("Doing other work in interface impl…");
}
}
[/java]
The above interface is still a valid functional interface. Now lets see how we can use the lambda expression as against anonymous inner class for implementing functional interfaces:
[java]
/*
* Implementing the interface by creating an
* anonymous inner class versus using
* lambda expression.
*/
public class SimpleFunInterfaceTest {
public static void main(String[] args) {
carryOutWork(new SimpleFuncInterface() {
@Override
public void doWork() {
System.out.println("Do in SimpleFun impl…");
}
});
carryOutWork(() -> System.out.println("Do in lambda exp impl…"));
}
public static void carryOutWork(SimpleFuncInterface sfi){
sfi.doWork();
}
}
[/java]
And the output would be …
[shell]
Do work in SimpleFun impl…
Do work in lambda exp impl…
[/shell]
In case you are using an IDE which supports the Java Lambda expression syntax(Netbeans 8 Nightly builds) then it provides an hint when you use an anonymous inner class as used above

This was a brief introduction to the concept of functional interfaces in java 8 and also how they can be implemented using Lambda expressions.

 

如果你正在浏览Java8的API,你会发现java.util.function中 Function, Supplier, Consumer, Predicate和其他函数式接口广泛用在支持lambda表达式的API中。这些接口有一个抽象方法,会被lambda表达式的定义所覆盖。在这篇文章中,我会简单描述Function接口,该接口目前已发布在java.util.function中。

Function接口的主要方法:

R apply(T t) – 将Function对象应用到输入的参数上,然后返回计算结果。

default ‹V› Function‹T,V› – 将两个Function整合,并返回一个能够执行两个Function对象功能的Function对象。

译者注:Function接口中除了apply()之外全部接口如下:

default <V> Function<T,V> andThen(Function<? super R,? extends V> after) 返回一个先执行当前函数对象apply方法再执行after函数对象apply方法的函数对象。

default <V> Function<T,V> compose(Function<? super V,? extends T> before)返回一个先执行before函数对象apply方法再执行当前函数对象apply方法的函数对象。

static <T> Function<T,T> identity() 返回一个执行了apply()方法之后只会返回输入参数的函数对象。

本章节将会通过创建接受Function接口和参数并调用相应方法的例子探讨apply方法的使用。我们同样能够看到API的调用者如何利用lambda表达式替代接口的实现。除了传递lambda表达式之外,API使用者同样可以传递方法的引用,但这样的例子不在本篇文章中。

如果你想把接受一些输入参数并将对输入参数处理过后的结果返回的功能封装到一个方法内,Function接口是一个不错的选择。输入的参数类型和输出的结果类型可以一致或者不一致。

一起来看看接受Function接口实现作为参数的方法的例子:

01 public class FunctionDemo {
02  
03     //API which accepts an implementation of
04  
05     //Function interface
06  
07     static void modifyTheValue(int valueToBeOperated, Function<Integer, Integer> function){
08  
09         int newValue = function.apply(valueToBeOperated);
10  
11         /*     
12          * Do some operations using the new value.     
13          */
14  
15         System.out.println(newValue);
16  
17     }
18  
19 }

下面是调用上述方法的例子:

01 public static void main(String[] args) {
02  
03     int incr = 20;  int myNumber = 10;
04  
05     modifyTheValue(myNumber, val-> val + incr);
06  
07     myNumber = 15;  modifyTheValue(myNumber, val-> val * 10);
08  
09     modifyTheValue(myNumber, val-> val - 100);
10  
11     modifyTheValue(myNumber, val-> "somestring".length() + val - 100);
12  
13 }

你可以看到,接受1个参数并返回执行结果的lambda表达式创建在例子中。这个例子的输入如下:

1 30
2  
3 150
4  
5 -85
6  
7 -75

Function接口 – Java8中java.util.function包下的函数式接口的更多相关文章

  1. Java中java.util.concurrent包下的4中线程池代码示例

    先来看下ThreadPool的类结构 其中红色框住的是常用的接口和类(图片来自:https://blog.csdn.net/panweiwei1994/article/details/78617117 ...

  2. JAVA8的java.util.function包 @FunctionalInterface

    1 函数式接口java.util.function https://www.cnblogs.com/CobwebSong/p/9593313.html 2 JAVA8的java.util.functi ...

  3. java.util.regex包下的Pattern类和Matcher类的使用总结

    一.介绍 Java正则表达式通过java.util.regex包下的Pattern类与Matcher类实现1.Pattern类用于创建一个正则表达式,也可以说创建一个匹配模式,它的构造方法是私有的,不 ...

  4. java.util.regex包下的Pattern和Matcher详解(正则匹配)

    java正则表达式通过java.util.regex包下的Pattern类与Matcher类实现(建议在阅读本文时,打开java API文档,当介绍到哪个方法时,查看java API中的方法说明,效果 ...

  5. java.util.concurrent包下集合类的特点与适用场景

    java.util.concurrent包,此包下的集合都不允许添加null元素 序号 接口 类 特性 适用场景 1 Queue.Collection ArrayBlockingQueue 有界.阻塞 ...

  6. Java:concurrent包下面的Map接口框架图(ConcurrentMap接口、ConcurrentHashMap实现类)

    Java集合大致可分为Set.List和Map三种体系,其中Set代表无序.不可重复的集合:List代表有序.重复的集合:而Map则代表具有映射关系的集合.Java 5之后,增加了Queue体系集合, ...

  7. Java:concurrent包下面的Collection接口框架图( CopyOnWriteArraySet, CopyOnWriteArrayList,ConcurrentLinkedQueue,BlockingQueue)

    Java集合大致可分为Set.List和Map三种体系,其中Set代表无序.不可重复的集合:List代表有序.重复的集合:而Map则代表具有映射关系的集合.Java 5之后,增加了Queue体系集合, ...

  8. JAVA8的java.util.function包

    一 概述 name type description Consumer Consumer< T > 接收T对象,不返回值 Predicate Predicate< T > 接收 ...

  9. jdk8中java.util.concurrent包分析

    并发框架分类 1. Executor相关类 Interfaces. Executor is a simple standardized interface for defining custom th ...

随机推荐

  1. Nancy总结(一)Nancy一个轻量的MVC框架

    Nancy是一个基于.net 和Mono 构建的HTTP服务框架,是一个非常轻量级的web框架. 设计用于处理 DELETE, GET, HEAD, OPTIONS, POST, PUT 和 PATC ...

  2. Struts2 中Parameters是如何获取值的

    刚刚学习struts2的知识,在练习struts2的默认语言OGNL过程中,对于<p>parameters:<s:property value="#parameters.u ...

  3. VS中修改站点运行方式(集成 Or 经典)

    以前写过一篇博客使用HttpHander截取用户请求. 写进Web.Config时..运行会报 在集成环境下不能使用站点配置 就想改成经典..但是不会改..还修改过Framework配置什么的.. 那 ...

  4. XML模块

    XML 例子: # -*- encoding:utf-8 -*- import requests from xml.etree import ElementTree as ET f = request ...

  5. Java RMI 介绍和例子以及Spring对RMI支持的实际应用实例

    RMI 相关知识 RMI全称是Remote Method Invocation-远程方法调用,Java RMI在JDK1.1中实现的,其威力就体现在它强大的开发分布式网络应用的能力上,是纯Java的网 ...

  6. 说说C#的async和await(转)

    一个简单的例子: public class MyClass { public MyClass() { DisplayValue(); //这里不会阻塞 System.Diagnostics.Debug ...

  7. Properties类的使用方法

    它提供了几个主要的方法: 1. getProperty ( String key),用指定的键在此属性列表中搜索属性.也就是通过参数 key ,得到 key 所对应的 value. 2. load ( ...

  8. 工具介绍 - NimbleText

    非常实用的工具, 即使不是程序员也有必要掌握这个简单的小工具. 这个工具有桌面版和在线版两个版本. 桌面版地址: http://nimbletext.com/ 在线版地址: http://nimble ...

  9. 网站SEO优化之Robots.txt文件写法。

    作为网站开发者或网站管理员一定知道网站对搜索引擎的优化有多重要,好的网站不仅要有漂亮的界面,良好的用户体验,还要有较高的更新频率.要被百度.google这样的搜索引擎大量收录,才能增加网站展示量,访问 ...

  10. 【开源一个小工具】一键将网页内容推送到Kindle

    最近工作上稍微闲点,这一周利用下班时间写了一个小工具,其实功能挺简单但也小折腾了会. 工具名称:Simple Send to Kindle Github地址:https://github.com/zh ...