Lambda表达式

为什么使用lambda表达式

Lambda表达式可以简化我们的代码,使我们只需要关注主要的代码就可以。

//测试用的实体类

public class Employee {

    private String name;
private Integer age;
private double salary; public Employee() {
} public Employee(String name, Integer age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
}
//定义要操作的集合数据
List<Employee> employees = Arrays.asList( new Employee("张三",18,3000),
new Employee("李四",18,3000),
new Employee("张三",45,8700),
new Employee("王五",26,4500),
new Employee("麻子",30,2700),
new Employee("田七",15,200) );
//需求找出年龄大于20的员工

---------------最常规的操作--------

//过滤方法
public List<Employee> filterEmployee(List<Employee> employees){ ArrayList<Employee> list = new ArrayList<>();
for (Employee employee : employees) {
if(employee.getAge() > 20){
list.add(employee);
}
}
return list;
} //测试方法
@Test
public void test1(){
List<Employee> employees = filterEmployee(this.employees); for (Employee employee : employees) {
System.out.println(employee);
}
} //Employee{name='张三', age=45, salary=8700.0}
//Employee{name='王五', age=26, salary=4500.0}
//Employee{name='麻子', age=30, salary=2700.0} -------------第二种写法----------(策略模式) 1、先定义一个接口 public interface MyPredicate<T> { public boolean test(T t); } 2、定义过滤类实现我们定义的接口
public class FilterEmployeeByAge implements MyPredicate<Employee>{
@Override
public boolean test(Employee employee) { return employee.getAge()>20;
}
} 3、同样定义过滤方法
//过滤方法
public List<Employee> filterEmployee(List<Employee> employees, Mypredicatre<Employee> mp){ ArrayList<Employee> list = new ArrayList<>();
for (Employee employee : employees) {
if(mp.test){
list.add(employee);
}
}
return list;
} 4、测试方法 @Test
public void test2(){
List<Employee> employees = filterEmployee(this.employees, new FilterEmployeeByAge()); for (Employee employee : employees) {
System.out.println(employee);
}
} //Employee{name='张三', age=45, salary=8700.0}
//Employee{name='王五', age=26, salary=4500.0}
//Employee{name='麻子', age=30, salary=2700.0} -----------上面的方法每过滤不同的条件都要实现一个接口,不是很友好---------我们可以使用匿名内部类 @Test
public void test3(){
List<Employee> employees = filterEmployee(this.employees, new MyPredicate<Employee>() {
@Override
public boolean test(Employee employee) {
return employee.getAge() > 20;
}
}); -----------------匿名内部类可以使用lambda表达式简化----------
@Test
public void test4(){
List<Employee> employees = filterEmployee(this.employees, (e) -> e.getAge() > 20); for (Employee employee : employees) {
System.out.println(employee);
}
}

lambda表达式需要函数式接口支持。

函数式接口:只有一个方法的接口,可以用注解@FunctionalInterface修饰接口

语法格式:

  • 无参数,无返回值 ()->System.out.println("hello word")
    @Test
public void test(){
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("hello world");
}
};
//------------------lambda-----------------------------
Runnable r1 = ()-> System.out.println("hello world");
}
  • 有一个参数,无返回值 (x)-> System.out.println(x) (有一个参数小括号可以不写)
    @Test
public void test2(){
Consumer<String> con = (x)-> System.out.println(x);
//Consumer<String> con = x-> System.out.println(x);
con.accept("hello world");
}
  • 有两个参数,且有返回值 (有多条语句,必须使用{})
    @Test
public void test3(){
Comparator<Integer> com = (x,y)->{
System.out.println("函数式接口");
return Integer.compare(x,y);
};
}
  • 有两个参数,且有返回值,语句只有一条 (return 和{} 可以省略)
    @Test
public void test4(){
Comparator<Integer> com = (x,y)->Integer.compare(x,y);
}
  • lambda参数列表的数据类型可以省略不用写(类型推断)(要写都得写,不能写一个,一个不写)

java8中4大核心接口

Consumer : 消费型接口

​ void accept(T t);

    @Test
public void test4(){
happy(1000,(m) -> System.out.println("你消费了:"+m+"元"));
} public void happy(double money, Consumer<Double> con){
con.accept(money);
}

Supplier : 供给型接口

​ T get();

    @Test
//获取随机数
public void test5() {
List<Integer> numList = getNumList(5, () -> (int) (Math.random() * 10));
System.out.println(numList.toString());
}
//产生整数集合
public List<Integer> getNumList(int num, Supplier<Integer> sup) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < num; i++) {
list.add(sup.get());
}
return list;
}

Function<T,R>: 函数式接口

​ R apply(T t);

    @Test
public void test6(){
String str = strHandle("hello world", (s) -> s.substring(2, 5));
System.out.println(str);
}
//对字符串进行处理返回一个字符串
public String strHandle(String str, Function<String,String> fun){
return fun.apply(str);
}

Predicate: 断言型接口

​ boolean test(T t);

    @Test
public void test7(){
List<String> strings = Arrays.asList("hello", "world", "qw", "das", "s", "sadui");
List<String> str = filterStr(strings, (s) -> s.length() > 3);
System.out.println(str.toString());
}
//对字符串数组进行过滤
public List<String> filterStr(List<String> str, Predicate<String> pre){
ArrayList<String> list = new ArrayList<>(); for (String s : str) {
if(pre.test(s)){
list.add(s);
}
}
return list;
}

方法引用: 如果lambda体中的内容方法已经实现我们可以使用方法引用。

​ lambda表达式的另一种表现形式,

主要有三种语法格式:

Lambda体中方法的返回值要与实例方法返回值类型一致

  • 对象::实例方法名

@Test
public void test8(){
Consumer<String> con = (s) -> System.out.println(s); Consumer<String> con1 = System.out::println; PrintStream ps = System.out;
Consumer<String> con2 = ps::println; Employee emp = new Employee();
Supplier<Integer> sup = () -> emp.getAge();
Integer age = sup.get(); Supplier<Integer> sup1 = emp::getAge();
Integer age1 = sup1.get(); }
  • 类::静态方法名
    @Test
public void test9(){
Comparator<Integer> com = (x,y)-> Integer.compare(x,y); Comparator<Integer> com1 = Integer::compare; }
  • 类::实例方法名

    第一个参数是实例方法的调用者,第二参数是实例方法的参数才可以使用

    @Test
public void test10(){
BiPredicate<String,String> pre = (x,y)-> x.equals(y); BiPredicate<String,String> pre1 = String::equals; }

构造器引用:

className::new

​ 需要调用的构造器函数列表要与函数式接口中的抽象方法的参数列表保持一致

	@Test
public void test1(){ Supplier<Employee> sup = () -> new Employee(); //调用的是无参构造器
Supplier<Employee> sup1 = Employee::new; //调用的是带有一个参数的构造器
Function<Integer,Employee> fun = Employee::new; }

数组引用:

Type[]::new

	@Test
public void test1(){ Function<Integer,String[]> fun = (x)-> new String[x]; Function<Integer,String[]> fun1 = String[]::new; }

最新文章

  1. MVC -- 后台RedirectToAction传递实体类与字符串
  2. VS2013打开项目Web加载失败
  3. JAVA的界面(Swing)
  4. mysqli的增强功能
  5. LeetCode132:Palindrome Partitioning II
  6. 多线程并发流程控制之dispatch_group 有关函数
  7. 12. Integer to Roman
  8. Xlib: connection to &quot;:0.0&quot; refused by server Xlib: No protocol specified解决方案
  9. 云服务器 ECS Linux 服务器修改时区的两种方式
  10. showModalDialog 超过问题
  11. spring @Autowired或@Resource 的区别
  12. 新生命组件XAgent使用心得
  13. 极光的开源礼物「Aurora IMUI」
  14. vue项目实战总结
  15. python书籍推荐:Head First Python(中文版)
  16. array_diff()
  17. 章节七、6-Map集合的区别
  18. 高斯消元模板!!!bzoj1013
  19. 关于 ArrayList.toArray() 和 Arrays.asList().toArray()方法
  20. IDA的头像

热门文章

  1. Codeforces1132A——Regular Bracket Sequence(水题)
  2. Sublime Text3快速创建HTML5框架
  3. Git从远程仓库克隆
  4. 后缀数组【原理+python代码】
  5. linux中网络存储与考试系统搭建(实现多用户可以共享文件)
  6. &lt;学习opencv&gt;图像、视频和数据文件
  7. MyBatis练习——使用MyBatis查询所有职员信息
  8. Hive安装Version2.1.0
  9. 基于GO语言的PBFT共识算法
  10. VirtualBox 虚拟机怎样设置共享文件夹