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 ...
随机推荐
- c# 有无符号值进一步了解
1.编写过程中用到了short类型(有符号型,值范围含负值).两个正数之和得负. 改为int或unsigned short 均可. 2.注意,short型(-32768,32767)举例:做自加运算, ...
- linux下php环境配置
参: http://www.laozuo.org/5542.html LAMP,基于Linux/Apache/MySQL/PHP架构的网站建设环境,对于一般的网站来说足够使用,如果我们的网站访问量或者 ...
- Mac OS安装Scrapy失败
报错: DEPRECATION: Uninstalling a distutils installed project (six) has been deprecated and will be re ...
- java 字符串—数字常用处理
// 判断一个字符串是否都为数字 public boolean isDigit(String strNum) { return strNum.matches("[0-9]{1,}" ...
- C#中整型数据类型
C#中整型数据类型byte是8位的无符号整数,可是它表示的值的范围是0-255才3位啊怎么说是8位啊?谁能帮我解答 全部答案 八位二进制.0000 0000到1111 1111相当于十进制0-25 ...
- Oracle触发器实现监控某表的CRUD操作
前提:请用sys用户dba权限登录 1.创建一个表来存储操作日志 create table trig_sql( LT DATE not null primary key, SID NUMBER, SE ...
- 【bzoj2938】[Poi2000]病毒 AC自动机
题目描述 二进制病毒审查委员会最近发现了如下的规律:某些确定的二进制串是病毒的代码.如果某段代码中不存在任何一段病毒代码,那么我们就称这段代码是安全的.现在委员会已经找出了所有的病毒代码段,试问,是否 ...
- poj2018——Best Cow Fences
Description Farmer John's farm consists of a long row of N (1 <= N <= 100,000)fields. Each fie ...
- 虚拟机如何进入BIOS
- 【BZOJ1941】Hide and Seek(KD-Tree)
[BZOJ1941]Hide and Seek(KD-Tree) 题面 BZOJ 洛谷 题解 \(KD-Tree\)对于每个点搜一下最近点和最远点就好了 #include<iostream> ...