java functional syntax overview
Defining a Functional Interface
@FunctionalInterface
public interface TailCall<T> {
TailCall<T> apply();
default boolean isComplete() { return false; }
//...
}
A functional interface must have one abstract—unimplemented—method. It may have zero or more default or implemented methods. It may also have static methods.
Creating No-Parameter Lambda Expressions
lazyEvaluator(() -> evaluate(1), () -> evaluate(2));
The parentheses () around the empty parameters list are required if the lambda expression takes no parameters. The -> separates the parameters from the body of a lambda expression.
Creating a Single-Parameter Lambda Expression
friends.forEach((final String name) -> System.out.println(name));
The Java compiler can infer the type of lambda expression based on the context. In some situations where the context is not adequate for it to infer or we want better clarity, we can specify the type in front of the parameter names.
Inferring a Lambda Expression’s Parameter Type
friends.forEach((name) -> System.out.println(name));
The Java compiler will try to infer the types for parameters if we don’t provide them. Using inferred types is less noisy and requires less effort, but if we specify the type for one parameter, we have to specify it for all parameters in a lambda expression.
Dropping Parentheses for a Single-Parameter Inferred Type
friends.forEach(name -> System.out.println(name));
The parentheses () around the parameter is optional if the lambda expression takes only one parameter and its type is inferred. We could write name -> ... or (name) -> ...; lean toward the first since it’s less noisy.
Creating a Multi-Parameter Lambda Expression
friends.stream()
.reduce((name1, name2) ->
name1.length() >= name2.length() ? name1 : name2);
The parentheses () around the parameter list are required if the lambda expression takes multiple parameters or no parameters.
Calling a Method with Mixed Parameters
friends.stream()
.reduce("Steve", (name1, name2) ->
name1.length() >= name2.length() ? name1 : name2);
Methods can have a mixture of regular classes, primitive types, and functional interfaces as parameters. Any parameter of a method may be a functional interface, and we can send a lambda expression or a method reference as an argument in its place.
Storing a Lambda Expression
final Predicate<String> startsWithN = name -> name.startsWith("N");
To aid reuse and to avoid duplication, we often want to store lambda expressions in variables.
Creating a Multiline Lambda Expression
FileWriterEAM.use("eam2.txt", writerEAM -> {
writerEAM.writeStuff("how");
writerEAM.writeStuff("sweet");
});
We should keep the lambda expressions short, but it’s easy to sneak in a few lines of code. But we have to pay penance by using curly braces {}, and the return keyword is required if the lambda expression is expected to return a value.
Returning a Lambda Expression
public static Predicate<String> checkIfStartsWith(final String letter) {
return name -> name.startsWith(letter);
}
If a method’s return type is a functional interface, we can return a lambda expression from within its implementation.
Returning a Lambda Expression from a Lambda Expression
final Function<String, Predicate<String>> startsWithLetter =
letter -> name -> name.startsWith(letter);
We can build lambda expressions that themselves return lambda expressions. The implementation of the Function interface here takes in a String letter and returns a lambda expression that conforms to the Predicate interface.
Lexical Scoping in Closures
public static Predicate<String> checkIfStartsWith(final String letter) {
return name -> name.startsWith(letter);
}
From within a lambda expression we can access variables that are in the enclosing method’s scope. For example, the variable letter in the checkIfStartsWith() is accessed within the lambda expression. Lambda expressions that bind to variables in enclosing scopes are called closures.
Passing a Method Reference of an Instance Method
friends.stream().map(String::toUpperCase);
We can replace a lambda expression with a method reference if it directly routes the parameter as a target to a simple method call. The preceding sample code given is equivalent to this:
friends.stream().map(name -> name.toUpperCase());
Passing a Method Reference to a static Method
str.chars().filter(Character::isDigit);
We can replace a lambda expression with a method reference if it directly routes the parameter as an argument to a static method. The preceding sample code is equivalent to this:
str.chars().filter(ch -> Character.isDigit(ch));
Passing a Method Reference to a Method on Another Instance
str.chars().forEach(System.out::println);
We can replace a lambda expression with a method reference if it directly routes the parameter as an argument to a method on another instance; for example, println() on System.out. The preceding sample code is equivalent to this:
str.chars().forEach(ch -> System.out.println(ch));
Passing a Reference of a Method That Takes Parameters
people.stream()
.sorted(Person::ageDifference)
We can replace a lambda expression with a method reference if it directly routes the first parameter as a target of a method call, and the remaining parameters as this method’s arguments. The preceding sample code is equivalent to this:
people.stream()
.sorted((person1, person2) -> person1.ageDifference(person2))
Using a Constructor Reference
Supplier<Heavy> supplier = Heavy::new;
Instead of invoking a constructor, we can ask the Java compiler to create the calls to the appropriate constructor from the concise constructor-reference syntax. These work much like method references, except they refer to a constructor and they result in object instantiation. The preceding sample code is equivalent to this:
Supplier<Heavy> supplier = () -> new Heavy();
Function Composition
symbols
.map(StockUtil::getPrice)
.filter(StockUtil.isPriceLessThan(500))
.reduce(StockUtil::pickHigh)
.get();
We can compose functions to transform objects through a series of operations like in this example. In the functional style of programming, function composition or chaining is a very powerful construct to implement associative operations.
java functional syntax overview的更多相关文章
- Learning Java 8 Syntax (Java in a Nutshell 6th)
Java is using Unicode set Java is case sensitive Comments, C/C++ style abstract, const, final, int, ...
- Java & XML Tool Overview
As mentioned in the introduction Sun now provides these tools for XML Processing in Java: StAX Reade ...
- 【转】Java IO流 overview
Java流操作有关的类或接口: Java流类图结构: 流的概念和作用 流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象.即数据在两设备间的传输称为流,流的本质是数据传输,根据数据传输 ...
- Functional Java 学习笔记
Functional Java Functional Java是一个在Java语言中实现函数型编程范式的类库. 从接口上看,该类库似乎与Haskell语言关系密切,接口的方法名很多来自该语言. < ...
- java url demo
// File Name : URLDemo.java import java.net.*; import java.io.*; public class URLDemo { public stati ...
- Thinking in Java——笔记(12)
Error Handling with Exceptions The ideal time to catch an error is at compile time, before you even ...
- [开源框架推荐]Icepdf:纯java的pdf文档的提取和转换库
ICEpdf 是一个轻量级的开源 Java 语言的 PDF 类库.通过 ICEpdf 可以用来浏览.内容提取和转换 PDF 文档,而无须一些本地PDF库的支持. 可以用来做什么? 1.从pdf文件中提 ...
- 摘自:java夜未眠之java学习之道
目前Java可以说是产业界和学术界最热门的语言,许多读者都很急切想把Java学好.除非是武侠小说中的运功传送内力的方式,否则花上一段时间苦学是免不了的.花时间,不打紧,就是怕方法错误,事倍功半.我认为 ...
- [Java Basics] Stack, Heap, Constructor, I/O, Immutable, ClassLoader
Good about Java: friendly syntax, memory management[GC can collect unreferenced memory resources], o ...
随机推荐
- System.exit(0)
表示程序正常退出 System.exit(status) 当status非0时,表示程序为非正常退出. status=0, 关闭当前正在运行的虚拟机. 求质因数分解的程序如下: 两种算法: 一种是用S ...
- C# 实现对接电信交费易自动缴费
他有这样一个JS PassGuardCtrl.js 部分代码 1 defaults:{ 2 obj:null, 3 random:null,/ ...
- UVa 1400 (线段树) "Ray, Pass me the dishes!"
求一个区间的最大连续子序列,基本想法就是分治,这段子序列可能在区间的左半边,也可能在区间的右半边,也有可能是横跨区间中点,这样就是左子区间的最大后缀加上右子区间的最大前缀之和. 线段树维护三个信息:区 ...
- BZOJ2226: [Spoj 5971] LCMSum
题解: 考虑枚举gcd,然后问题转化为求<=n且与n互质的数的和. 这是有公式的f[i]=phi[i]*i/2 然后卡一卡时就可以过了. 代码: #include<cstdio> # ...
- HDU 5294 Tricks Device (最短路,最大流)
题意:给一个无向图(连通的),张在第n个点,吴在第1个点,‘吴’只能通过最短路才能到达‘张’,两个问题:(1)张最少毁掉多少条边后,吴不可到达张(2)吴在张毁掉最多多少条边后仍能到达张. 思路:注意是 ...
- Android02--debug.keystore的注册信息
1 -- 签名文件的密钥 默认签名文件的密码是:android 该文件的存放点是: 2 -- 签名文件的签名信息 keytool -list -v -keystore C:\Users\motadou ...
- MySQL基础之第4章 MySQL数据类型
4.1.整数类型 tinyint(4)smallint(6)mediumint(9)int(11)bigint(20) 注意:后面的是默认显示宽度,以int为例,占用的存储字节数是4个,即4*8=32 ...
- spring3.0.5的aop使用
spring3.0.5开始支持jpa2.0了,但是最近笔者在使用他的的时候发现了3.0.5的包与2.5.5相比,有所精简.其他外部的包,我们需要自己下载. AOP必须的spring包 org.spri ...
- 用ioctl获取无线网络信息 /usr//include/linux/wireless.h
1.UNIX Network Programming环境搭建 Unix NetWork Programming――环境搭建(解决unp.h等源码编译问题) http://blog.csdn.net/a ...
- POJ 1173 Find them, Catch them
题意:有两个帮派,每个人只属于一个帮派,m次操作,一种操作告诉你两个人不是一个帮派的,另一种操作问两个人是不是在一个帮派. 解法:并查集+向量偏移.偏移量表示和根节点是不是同一帮派,是为0,不是为1. ...