0

0

Java8中lambda表达式的使用方法

黄舟

黄舟

发布时间:2017-09-19 10:34:58

|

1513人浏览过

|

来源于php中文网

原创

java8最值得学习的特性就是lambda表达式,下面这篇文章主要给大家介绍了关于java8学习教程之lambda表达式使用的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。

前言

我们在 上一篇文章 中介绍了 lambda 表达式的语法,引入了 lambda 表达式的使用场景,以及使用 lambda 表达式的好处。我们将在这篇文章中,已实例讲解如何定义和使用 lambda 表达式,以及与其它语言相比,lambda 表达式在 Java 中的特殊规范。

使用匿名内部类的例子

首先明确一点,在 Java8 出现之前,lambda 表达式能够做到的,使用内部类也能做到,lambda 表达式只是简化了编程。
下面的例子是从列表中根据条件挑选出读者。

立即学习Java免费学习笔记(深入)”;

定义 TantanitReader:


public class TantanitReader {
 private int age;
 private String loginName;
 private String realName;
 private String career;

 public TantanitReader() {
 }

 public TantanitReader(int age, String loginName, String realName, String career) {
 this.age = age;
 this.loginName = loginName;
 this.realName = realName;
 this.career = career;
 }

 public int getAge() {
 return age;
 }

 public void setAge(int age) {
 this.age = age;
 }

 public String getLoginName() {
 return loginName;
 }

 public void setLoginName(String loginName) {
 this.loginName = loginName;
 }

 public String getRealName() {
 return realName;
 }

 public void setRealName(String realName) {
 this.realName = realName;
 }

 public String getCareer() {
 return career;
 }

 public void setCareer(String career) {
 this.career = career;
 }

 @Override
 public String toString() {
 return "age:"+this.getAge()+",loginName:"+this.loginName
 +",realName:"+this.getRealName()+",career:"+this.getCareer();
 }
}

定义判断的接口:


public interface Predicate {
 boolean test(T t);
}

定义选择函数:


public class SelectService {
 public List select(Collection source, Predicate predicate){
 List result = new LinkedList();
 for(T element:source){
  if (predicate.test(element)) {
  result.add(element);
  }
 }
 return result;
 }

}

编写测试用的例子,分别选择成年读者和十多岁(包括 10 岁)的读者:


public class TantanitReaderPredicateTest {


 public static void main(String[] args) {
 SelectService tantanitReaderSelectSerive
 =new SelectService();
 List source = new LinkedList<>();
 source.add(new TantanitReader(10,"jack","张三","学生"));
 source.add(new TantanitReader(18,"rose","李四","学生"));
 source.add(new TantanitReader(19,"mike","王五","程序员"));
 source.add(new TantanitReader(20,"jack","赵六","作家"));

 List audultReaders
 =tantanitReaderSelectSerive.select(source, new Predicate() {
  @Override
  public boolean test(Object o) {
  TantanitReader tantanitReader=(TantanitReader)o;
  return tantanitReader.getAge()>=18;
  }
 });
 System.out.println("tantanit.com 成年读者名单如下:");
 printTantanitReaders(audultReaders);

 System.out.println("tantanit.com 十多岁(包含 10 岁)成员如下:");
 List teenReaders
 =tantanitReaderSelectSerive.select(source, new Predicate() {
  @Override
  public boolean test(Object o) {
  TantanitReader tantanitReader=(TantanitReader)o;
  return tantanitReader.getAge()>=10 && tantanitReader.getAge()<=19;
  }
 });
 printTantanitReaders(teenReaders);
 }


 public static void printTantanitReaders(List tantanitReaders) {
 for (TantanitReader tantanitReader : tantanitReaders) {
  System.out.println(tantanitReader.toString());
 }
 }


}

执行后,打印结果如下:


tantanit.com 成员读者名单如下:
age:18,loginName:rose,realName: 李四,career: 学生 
age:19,loginName:mike,realName: 王五,career: 程序员
age:20,loginName:jack,realName: 赵六,career: 作家
tantanit.com 十多岁(包含10 岁)成员如下:
age:10,loginName:jack,realName: 张三,career: 学生
age:18,loginName:rose,realName: 李四,career: 学生
age:19,loginName:mike,realName: 王五,career: 程序员

可以看到,两次选择读者,都需要 new Predicate(),并且重写(Override)test 方法,而真正的差异其实只在于判断语句:


tantanitReader.getAge()>=18


tantanitReader.getAge()>=10 && tantanitReader.getAge()<=19

但是在 Java8 之前,由于没有 lambda 表达式,只能忍受这种冗余。如何用 lambda 表达式来简化代码呢?

为了照顾 Java 开发人员既有的编程习惯,与其它语言不同,Java8 在设计 lambda 表达式的使用机制时,规定仍然需要使用接口,并且要求所使用的接口必须是函数式接口,在这个例子中,我们仍然可以使用:


public interface Predicate {
 boolean test(T t);
}

因为这个接口只有一个抽象方法(java8 引入了 default 方法,default 方法有具体实现,不算抽象方法),所以它是函数式接口(functional interface)。函数式接口可以加上 @FunctionalInterface 声明,也可以不加。但是加上之后,编译器在编译阶段就会检查这个接口是否符合函数式接口的定义,所以这里我们定义一个新的接口,并且加上 @FunctionalInterface 声明:

网钛淘拍CMS(TaoPaiCMS) V1.60
网钛淘拍CMS(TaoPaiCMS) V1.60

2013年07月06日 V1.60 升级包更新方式:admin文件夹改成你后台目录名,然后补丁包里的所有文件覆盖进去。1.[新增]后台引导页加入非IE浏览器提示,后台部分功能在非IE浏览器下可能没法使用2.[改进]淘客商品管理 首页 列表页 内容页 的下拉项加入颜色来区别不同项3.[改进]后台新增/修改淘客商品,增加淘宝字样的图标和天猫字样图标改成天猫logo图标4.[改进]为统一名称,“分类”改

下载


@FunctionalInterface
public interface PredicateFunction {
 boolean test(T t);
}

并且给 SelectService 添加一个以 PredicateFunction 为参数的方法:


public List select(Collection source, PredicateFunction predicate){
 List result = new LinkedList();
 for(T element:source){
 if (predicate.test(element)) {
  result.add(element);
 }
 }
 return result;
}

再修改测试的例子:


public class TantanitReaderPredicateFunctionTest {

 public static void main(String[] args) {
 SelectService tantanitReaderSelectSerive
 =new SelectService();
 List source = new LinkedList<>();
 source.add(new TantanitReader(10,"jack","张三","学生"));
 source.add(new TantanitReader(18,"rose","李四","学生"));
 source.add(new TantanitReader(19,"mike","王五","程序员"));
 source.add(new TantanitReader(20,"jack","赵六","作家"));

 PredicateFunction predicateFunction
  = (TantanitReader tantanitReader) -> tantanitReader.getAge() >= 18;
 List audultReaders
 =tantanitReaderSelectSerive.select(source,predicateFunction);

 System.out.println("tantanit.com 成员读者名单如下:");
 printTantanitReaders(audultReaders);

 System.out.println("tantanit.com 十多岁(包含 10 岁)成员如下:");
 PredicateFunction predicateFunction2
 = (TantanitReader tantanitReader)
 -> tantanitReader.getAge()>=10 && tantanitReader.getAge()<=19;
 List teenReaders
 =tantanitReaderSelectSerive.select(source,predicateFunction2);
 printTantanitReaders(teenReaders);
 }


 public static void printTantanitReaders(List tantanitReaders) {
 for (TantanitReader tantanitReader : tantanitReaders) {
  System.out.println(tantanitReader.toString());
 }
 }

}

下面我们分析一下这段代码是如何生效的:


PredicateFunction predicateFunction
 = (TantanitReader tantanitReader) -> tantanitReader.getAge() >= 18;
List audultReaders
=tantanitReaderSelectSerive.select(source,predicateFunction);

这段代码,生成了一个 PredicateFunction 类型的实例,并且将该实例的引用作为参数传给 tantanitReaderSelectSerive 的 select 方法,并且执行 select 方法。select 在执行过程中,调用 predicateFunction 的 test 方法,而 test 方法的内容就是我们传入的 lambda 表达式,最终按照 lambda 表达式,选择出读者。

再进一步,一般可以不定义 predicateFunction 这个变量,而直接将 lambda 表达式作为参数传给 tantanitReaderSelectSerive 的 select 方法,像这样:


List audultReaders
=tantanitReaderSelectSerive.select(
 source,(TantanitReader tantanitReader) -> tantanitReader.getAge() >= 18
);

但是这个例子,实际上会报编译错误,说 TantanitReader 和 tantanitReaderSelectSerive 的 select 方法的定义不匹配,因为 select 方法使用的是泛型。java8 的文档确实是规定了在使用泛型的情况下,不能直接将 lambda 表达式作为参数,这个挺无语的。如果不使用泛型的,没有这个问题。

小结

下面总结一下如何使用 lambda 表达式

  • 首先,定义一个函数式接口(functional interface),并且在接口中定义需要使用的抽象方法。

  • 编写业务方法,并且以该函数式接口作为参数,并且调用该接口定义的方法,完成业务逻辑。

  • 调用业务方法,并且将 lambda 表达式作为参数传入。

如果使用了泛型,最后一步改为先定义一个函数式接口的实例的引用,再作为参数传给业务方法。

此外,lambda 表达式还可以继续简化为函数引用,将在后面的文章中讲解。

总结

相关文章

java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

129

2025.12.31

php网站源码教程大全
php网站源码教程大全

本专题整合了php网站源码相关教程,阅读专题下面的文章了解更多详细内容。

77

2025.12.31

视频文件格式
视频文件格式

本专题整合了视频文件格式相关内容,阅读专题下面的文章了解更多详细内容。

81

2025.12.31

不受国内限制的浏览器大全
不受国内限制的浏览器大全

想找真正自由、无限制的上网体验?本合集精选2025年最开放、隐私强、访问无阻的浏览器App,涵盖Tor、Brave、Via、X浏览器、Mullvad等高自由度工具。支持自定义搜索引擎、广告拦截、隐身模式及全球网站无障碍访问,部分更具备防追踪、去谷歌化、双内核切换等高级功能。无论日常浏览、隐私保护还是突破地域限制,总有一款适合你!

60

2025.12.31

出现404解决方法大全
出现404解决方法大全

本专题整合了404错误解决方法大全,阅读专题下面的文章了解更多详细内容。

444

2025.12.31

html5怎么播放视频
html5怎么播放视频

想让网页流畅播放视频?本合集详解HTML5视频播放核心方法!涵盖<video>标签基础用法、多格式兼容(MP4/WebM/OGV)、自定义播放控件、响应式适配及常见浏览器兼容问题解决方案。无需插件,纯前端实现高清视频嵌入,助你快速打造现代化网页视频体验。

15

2025.12.31

关闭win10系统自动更新教程大全
关闭win10系统自动更新教程大全

本专题整合了关闭win10系统自动更新教程大全,阅读专题下面的文章了解更多详细内容。

12

2025.12.31

阻止电脑自动安装软件教程
阻止电脑自动安装软件教程

本专题整合了阻止电脑自动安装软件教程,阅读专题下面的文章了解更多详细教程。

5

2025.12.31

html5怎么使用
html5怎么使用

想快速上手HTML5开发?本合集为你整理最实用的HTML5使用指南!涵盖HTML5基础语法、主流框架(如Bootstrap、Vue、React)集成方法,以及无需安装、直接在线编辑运行的平台推荐(如CodePen、JSFiddle)。无论你是新手还是进阶开发者,都能轻松掌握HTML5网页制作、响应式布局与交互功能开发,零配置开启高效前端编程之旅!

2

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
极客学院Java8新特性视频教程
极客学院Java8新特性视频教程

共17课时 | 3.7万人学习

极客学院Java8新特性视频教程
极客学院Java8新特性视频教程

共17课时 | 3.7万人学习

CSS3 教程
CSS3 教程

共18课时 | 4.2万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号