lambda表达式的应用例子和JavaSE 8特性
在JavaSE 8 引入了lambda表达式,lambda表达式的引入带来的好处是:通过语法上的改进,减少开发人员需要编写和维护的代码数量。这个在下面使用和不使用lambda的对比中可以清晰看出来。
1.
public class RunnableTest {
public static void main(String[] args){
System. out.println("===============RunnableTest=================" );
//Anonymous Runnable
Runnable r1 = new Runnable(){
@Override
public void run(){
System. out.println("Hello world, I am runnable one." );
}
};
//Lambda Runnable
Runnable r2 = ()->System. out.println("Hello world, I am runnable two");
r1.run();
r2.run();
}
}
public class ComparatorTest {
public static void main(String[] args) {
List<Person> personList = Person.createShortList();
// Sort with Inner Class
Collections.sort(personList , new Comparator<Person>(){
public int compare(Person p1 , Person p2){
return p1 .getSurName().compareTo(p2.getSurName());
}
});
System.out.println( "=== Sorted Asc SurName ===");
for(Person p: personList){
p.printName();
}
// Use Lambda instead
// Print Asc
System.out.println( "=== Sorted Asc SurName ===");
Collections.sort(personList , (Person p1, Person p2) -> p1.getSurName().compareTo(p2 .getSurName()));
for(Person p: personList){
p.printName();
}
// Print Desc
System.out.println( "=== Sorted Desc SurName ===");
Collections.sort(personList , (p1 , p2 ) -> p2.getSurName().compareTo(p1 .getSurName()));
for(Person p: personList){
p.printName();
}
}
}
(int x, int y) |
-> |
x + y |
| Argument List | Arrow Token | Body |
/**
* @author MikeW
*/
public interface MyTest<T> {
public boolean test(T t );
} /**
*
* @author MikeW
*/
public class RoboContactAnon { public void phoneContacts(List<Person> pl , MyTest<Person> aTest){
for(Person p: pl){
if (aTest.test(p)){
roboCall( p);
}
}
} public void emailContacts(List<Person> pl , MyTest<Person> aTest){
for(Person p: pl){
if (aTest.test(p)){
roboEmail( p);
}
}
} public void mailContacts(List<Person> pl , MyTest<Person> aTest){
for(Person p: pl){
if (aTest.test(p)){
roboMail( p);
}
}
} public void roboCall(Person p ){
System.out.println( "Calling " + p .getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p .getPhone());
} public void roboEmail(Person p ){
System.out.println( "EMailing " + p .getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p .getEmail());
} public void roboMail(Person p ){
System.out.println( "Mailing " + p .getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p .getAddress());
} } /**
* @author MikeW
*/
public class RoboCallTest03 { public static void main(String[] args) { List<Person> pl = Person. createShortList();
RoboContactAnon robo = new RoboContactAnon(); System.out.println( "\n==== Test 03 ====");
System.out.println( "\n=== Calling all Drivers ===" );
robo.phoneContacts( pl,
new MyTest<Person>(){
@Override
public boolean test(Person p){
return p .getAge() >=16;
}
}
); System.out.println( "\n=== Emailing all Draftees,Using Lambda Expression ===" );
MyTest<Person> allDraftees = (p )->p .getAge() >= 18 && p.getAge() <= 25 && p.getGender() == Gender.MALE;
robo.emailContacts( pl, allDraftees); System.out.println( "\n=== Mail all Pilots,Using Lambda Expression ===" );
robo.mailContacts( pl,( p)-> p.getAge() >= 23 && p.getAge() <= 65); }
}
/**
*
* @author MikeW
*/
public class RoboContactLambda {
public void phoneContacts(List<Person> pl , Predicate<Person> pred){
for(Person p: pl){
if (pred.test(p)){
roboCall( p);
}
}
} public void emailContacts(List<Person> pl , Predicate<Person> pred){
for(Person p: pl){
if (pred.test(p)){
roboEmail( p);
}
}
} public void mailContacts(List<Person> pl , Predicate<Person> pred){
for(Person p: pl){
if (pred.test(p)){
roboMail( p);
}
}
} public void roboCall(Person p ){
System.out.println( "Calling " + p .getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p .getPhone());
} public void roboEmail(Person p ){
System.out.println( "EMailing " + p .getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p .getEmail());
} public void roboMail(Person p ){
System.out.println( "Mailing " + p .getGivenName() + " " + p.getSurName() + " age " + p.getAge() + " at " + p .getAddress());
} } /**
*
* @author MikeW
*/
public class RoboCallTest04 { public static void main(String[] args){ List<Person> pl = Person. createShortList();
RoboContactLambda robo = new RoboContactLambda(); // Predicates
Predicate <Person> allDrivers = p -> p .getAge() >= 16;
Predicate <Person> allDraftees = p -> p .getAge() >= 18 && p.getAge() <= 25 && p.getGender() == Gender.MALE;
Predicate<Person> allPilots = new Predicate<Person>(){ @Override
public boolean test(Person p )
{ return p .getAge() >= 23 && p.getAge() <= 65;
}
}; System.out.println( "\n==== Test 04 ====");
System.out.println( "\n=== Calling all Drivers ===" );
robo.phoneContacts( pl, allDrivers); System.out.println( "\n=== Emailing all Draftees ===" );
robo.emailContacts( pl, allDraftees); System.out.println( "\n=== Mail all Pilots ===");
robo.mailContacts( pl, allPilots); // Mix and match becomes easy
System.out.println( "\n=== Mail all Draftees ===");
robo.mailContacts( pl, allDraftees); System.out.println( "\n=== Call all Pilots ===");
robo.phoneContacts( pl, allPilots); }
}
/**
* @author MikeW
*/
public class NameTestNew { public static void main(String[] args) { System.out.println( "\n==== NameTestNew ==="); List<Person> list1 = Person. createShortList(); // Print Custom First Name and e-mail
System.out.println( "===Custom List===");
for (Person person: list1){
System. out.println(
person. printCustom(p -> "Name: " + p.getGivenName() + " EMail: " + p.getEmail())
);
} // Define Western and Eastern Lambdas
Function<Person, String> westernStyle = p -> {
return "\nName: " + p .getGivenName() + " " + p.getSurName() + "\n" +
"Age: " + p .getAge() + " " + "Gender: " + p .getGender() + "\n" +
"EMail: " + p .getEmail() + "\n" +
"Phone: " + p .getPhone() + "\n" +
"Address: " + p .getAddress();
}; Function<Person,String> easternStyle = new Function<Person,String>(){ @Override
public String apply(Person p )
{
return "\nName: " + p .getSurName() + " "
+ p.getGivenName() + "\n" + "Age: " + p .getAge() + " " +
"Gender: " + p .getGender() + "\n" +
"EMail: " + p .getEmail() + "\n" +
"Phone: " + p .getPhone() + "\n" +
"Address: " + p .getAddress();
} }; // Print Western List
System.out.println( "\n===Western List===");
for (Person person: list1){
System. out.println(
person. printCustom(westernStyle)
);
} // Print Eastern List
System.out.println( "\n===Eastern List===");
for (Person person: list1){
System. out.println(
person. printCustom(easternStyle)
);
} }
}
/**
*
* @author MikeW
*/
public class SearchCriteria { private final Map<String, Predicate<Person>> searchMap = new HashMap<>(); private SearchCriteria() {
super();
initSearchMap();
} private void initSearchMap() {
Predicate<Person> allDrivers = p -> p .getAge() >= 16;
Predicate<Person> allDraftees = p -> p .getAge() >= 18 && p.getAge() <= 25 && p.getGender() == Gender.MALE;
Predicate<Person> allPilots = p -> p .getAge() >= 23 && p.getAge() <= 65; searchMap.put( "allDrivers", allDrivers );
searchMap.put( "allDraftees", allDraftees );
searchMap.put( "allPilots", allPilots ); } public Predicate<Person> getCriteria(String PredicateName) {
Predicate<Person> target; target = searchMap.get( PredicateName); if (target == null) { System. out.println("Search Criteria not found... " );
System.exit(1); } return target; } public static SearchCriteria getInstance() {
return new SearchCriteria();
}
}
/**
*
* @author MikeW
*/
public class Test02Filter { public static void main(String[] args) { List<Person> pl = Person. createShortList(); SearchCriteria search = SearchCriteria. getInstance(); System.out.println( "\n=== Western Pilot Phone List ===" ); pl.stream().filter(search .getCriteria("allPilots")).forEach(Person::printWesternName); System.out.println( "\n=== Eastern Draftee Phone List ===" ); pl.stream().filter(search .getCriteria("allDraftees")).forEach(Person::printEasternName);
//filter(Predicate<? super Person>)
//forEach(Consumer<? super Person>)
}
}
在Java SE 8 中,集合对象有流,使用流中的方法filter,可以筛选出符合筛选条件的元素。
参考资料:
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html
https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html
lambda表达式的应用例子和JavaSE 8特性的更多相关文章
- Java lambda 表达式详解(JDK 8 新特性)
什么是 lambda 表达式 lambda 表达式(拉姆达表达式)是 JAVA 8 中提供的一种新的特性,它使 Java 也能进行简单的"函数式编程". lambda 表达式的本质 ...
- Lambda 表达式的演示样例-来源(MSDN)
本文演示怎样在你的程序中使用 lambda 表达式. 有关 lambda 表达式的概述.请參阅 C++ 中的 Lambda 表达式. 有关 lambda 表达式结构的具体信息,请參阅 Lambda 表 ...
- C++11里面的Lambda表达式
Lambda Expressions in C++ C++中的Lambda表达式 In Visual C++, a lambda expression—referred to as a lambda— ...
- Java8(1)之Lambda表达式初步与函数式接口
Lambda表达式初步 介绍 什么是Lambda表达式? 在如 Lisp.Python.Ruby 编程语言中,Lambda 是一个用于表示匿名函数或闭包的运算符 为何需要lambda表达式? 在 Ja ...
- lambda表达式底层处理机制
为了支持函数式编程,Java 8引入了Lambda表达式,那么在Java 8中到底是如何实现Lambda表达式的呢? Lambda表达式经过编译之后,到底会生成什么东西呢? 在没有深入分析前,让我们先 ...
- lambda表达式/对象引用计数
★lambda表达式的用法例:I=[(lambda x: x*2),(lambda y: y*3)]调用:for x in I: print x(2)输出:4,6 ★获取对象的引用次数sys.getr ...
- Lambda 表达式的示例
本文中的过程演示如何使用 lambda 表达式. 有关 lambda 表达式的概述,请参见 C++ 中的 Lambda 表达式. 有关 lambda 表达式结构的更多信息,请参见 Lambda 表达式 ...
- JAVA8初探-让方法参数具备行为能力并引入Lambda表达式
关于JAVA8学习的意义先来贴一下某网站上的对它的简单介绍:“Java 8可谓Java语言历史上变化最大的一个版本,其承诺要调整Java编程向着函数式风格迈进,这有助于编写出更为简洁.表达力更强,并且 ...
- lambda函数、lambda表达式
C++11 新特性:Lambda 表达式 豆子 2012年5月15日 C++ 10条评论 参考文章:https://blogs.oracle.com/pcarlini/entry/c_1x_tidbi ...
随机推荐
- TCP系列13—重传—3、协议中RTO计算和RTO定时器维护
从上一篇示例中我们可以看到在TCP中有一个重要的过程就是决定何时进行超时重传,也就是RTO的计算更新.由于网络状况可能会受到路由变化.网络负载等因素的影响,因此RTO也必须跟随网络状况动态更新.如果T ...
- 最近面试js部分试题总结
二,JavaScript面试题总结 1,首先是数组去重算法:给一个数组,去掉重复值 (function() { var arr = [1, 2, 3, 3, 4, ]; function unique ...
- php缓存技术——memcache常用函数详解
php缓存技术——memcache常用函数详解 2016-04-07 aileen PHP编程 Memcache函数库是在PECL(PHP Extension Community Library)中, ...
- C# 使用this的形参
示例1: public static RectangleF TransformRect(this Matrix mat, RectangleF rect) 是向Matrix类扩展带有Rectangle ...
- 载入其他同名源文件导致vs编译错误
今天下午工程编译的时候总是通不过,提示1,某个类没有某个成员,可是我去该类的头文件下查看,确实包括了这个成员啊.2,没有某个类,可是我明明定义了的. 检查了好久才发现 原来是,我打开了其他工程下的某一 ...
- 第一章 Spring 概述
Spring框架的生态,已经成了JavaWeb开发的事实标准 以IOC与AOP为基础,提供了一整套JavaWeb的开发解决方案 在需要引入功能前,先看看有没有Spring的实现,或者其他框架,看看能否 ...
- Java notify的使用
半路出家学习java, 花了几分钟简单看了.在早上那个例子上稍微改了下, notify 对象上必须使用 synchronized 我的理解是在java synchronized只是个线程同步标志,但是 ...
- BZOJ4823 CQOI2017老C的方块(最小割)
如果将其转化为一个更一般的问题即二分图带权最小单边点覆盖(最小控制集)感觉是非常npc的.考虑原题给的一大堆东西究竟有什么奇怪的性质. 容易发现如果与特殊边相邻的两格子都放了方块,并且这两个格子都各有 ...
- 用select模拟一个socket server成型版
1.你往output里面放什么,下次循环就出什么. 2. 1.服务器端:实现了收和发的分开进行 import select,socket,queue server=socket.socket() s ...
- CentOS 转义字符
常用转义字符 反斜杠(\):使反斜杠后面的一个变量变为单纯的字符串. 单引号(''):转义其中所有的变量为单纯的字符串. 双引号(""):保留其中的变量属性,不进行转义处理. 反引 ...