Lambda表达式(3)——使用例子

本文深入探讨Java Lambda表达式在集合操作、线程实例化及系统内置函数式接口的应用,包括排序、遍历、条件删除及闭包概念,提供丰富的代码示例。

先给出Person类的代码:

package lambda;

public class Person {
 public String name;
 public int age;
 
 public Person() {
  System.out.println("Person类的无参构造方法执行了");
 }
 
 public Person(String name,int age) {
  this.name=name;
  this.age=age;
  System.out.println("Person类的有参构造方法执行了");
 }
 
 public String toString() {
  return "person{" + "name='"+name+'\''
    +", age="+age+"}";
 }
}
1.集合排序

package lambda;

import java.util.ArrayList;
public class Exercise1 {
 //集合排序
 //ArrayList<>
 public static void main(String[] args) {
  // 需求:已经在一个ArrayList中有若干个Person对象,将这些Person对象按照年龄进行降序排序
  ArrayList<Person> list=new ArrayList<>();
  
  list.add(new Person("xiaoming",10));
  list.add(new Person("lilei",11));
  list.add(new Person("hanmeimei",12));
  list.add(new Person("lili",9));
  list.add(new Person("Lucy",9));
  list.add(new Person("xiaolan",2));
  list.add(new Person("jan",40));
  
  //排序
  list.sort((o1,o2)->o2.age-o1.age);//
  
  System.out.println(list);
 }
}
2.TreeSet
package lambda;
import java.util.TreeSet;
public class Exercise2 {
 public static void main(String[] args) {
  // TreeSet
  //使用Lambda表达式来实现Comparator接口,并实例化一个TreeSet对象
  TreeSet<Person> set=new TreeSet<>((o1,o2)->{
   if(o1.age>=o2.age) {
    return -1;
   }
   else {
    return 1;
   }
  }); 
  set.add(new Person("xiao",10));
  set.add(new Person("lilei",11));
  set.add(new Person("hanmeimei",12));
  set.add(new Person("lili",9));
  set.add(new Person("Lucy",9));
  set.add(new Person("xiaolan",2));
  set.add(new Person("jan",40)); 
  System.out.println(set);
 }
}

多行共同编辑快捷键:Shift+Alt+A

3.集合的遍历forEach
package lambda;

import java.util.ArrayList;
import java.util.Collections;
public class Exercise3 {
 public static void main(String[] args) {
  // 集合的遍历
  
  ArrayList<Integer> list =new ArrayList<>();
  Collections.addAll(list, 1,2,3,4,5,6,7,8,9,0); 
  
  //将集合中的每一个元素都带入到方法accept中
  list.forEach(System.out::println); 
  
  //输出集合中所有的偶数
  list.forEach(ele->{
   if(ele%2==0) {
    System.out.println(ele);
   }
  });
 }
}
4.removeIf
package lambda;

import java.util.ArrayList;
import java.util.ListIterator;

public class Exercise4 {
 public static void main(String[] args) {
  //需求:删除集合中满足条件的元素
  ArrayList<Person> list=new ArrayList<>();
  list.add(new Person("xiao",10));
  list.add(new Person("lilei",11));
  list.add(new Person("hanmeimei",12));
  list.add(new Person("lili",9));
  list.add(new Person("Lucy",9));
  list.add(new Person("xiaolan",2));
  list.add(new Person("jan",40));
  
  //删除集合中年龄大于10岁的元素
//  ListIterator<Person> it = list.listIterator();
//  while(it.hasNext()) {
//   Person ele=it.next();
//   if(ele.age>10) {
//    it.remove();
//   }
//  }

  //lambda实现
  //将集合中的每一个元素都带入到test方法中,如果返回值是true,这删除这个元素
  list.removeIf(ele->ele.age>10);
  
  System.out.println(list);
 }
}
  
5. 线程实例化
package lambda;
//线程的实例化

public class Exercise5 {
 public static void main(String[] args) {
  //需求:开辟一条线程,做一个数字的输出 
  
  Thread t=new Thread(()->{
   for (int i=0;i<100;i++) {
    System.out.println(i);
   }
  }); 
   
  t.start();
  
 }
}
6.系统内置函数式接口
package lambda;
import java.util.function.*;
public class FunctionalInterface {
 public static void main(String[] args) {
  // 系统内置的一些函数式接口
  
  //Predicate<T>           :       参数T 返回值boolean
  //      IntPredicate             int -> boolean
  //      LongPredicate            long -> boolean
  //      DoublePredicate          duble -> boolean
  
  //Consumer<T>            :       参数T 返回值void
  //  IntConsumer              int -> void
  //      LongConsumer             Long -> void
  //      DoubleConsumer           double -> void
  
  //Function<T,R>          :       参数T 返回值R
  //      IntFunction<R>           int -> R
  //      LongFunction<R>          long -> R
  //      DoubleFunction<R>        double -> R
  //      IntToLongFunction        int -> long
  //      IntToDoubleFunction      int -> double
  //      LongToIntFunction        long -> int
  //      LongToDoubleFunction     long -> double
  //      DoubleToIntFunction      double -> int
  //      DoubleToLongFunction     double ->long
  
  //Supplier<T>            :       参数无 返回值T
  //UnaryOperator<T>       :       参数T 返回值T
  //BinaryOperator<T>      :       参数T,T 返回值T
  //BiFunction<T,U,R>      :       参数T,U 返回值R
  //BiPredicate<T,U>       :       参数T,U 返回值Boolean
  //BiConsumer<T,U>        :       参数T,U 返回值void
  
  //比较常用的
  //Predicate<T>  、  Consumer<T>  、  Function<T,R>  、 Supplier<T>
 }
}
7.闭包

关于代码块以及自由变量值有一个术语:闭包
在java中,Lambda表达式就是闭包。

package lambda;

import java.util.function.Supplier;

public class ClosureDemo {
 public static void main(String[] args) {
  //闭包
  
  int n=getNumber().get();  
  System.out.println(n);
 } 
 
 private static Supplier<Integer> getNumber(){
  int num=10;  
  
  return ()->{
   return num;  //返回这个方法本身的变量10
  };
 }
}
package lambda;

import java.util.function.Consumer;

public class ClosureDemo2 {
 public static void main(String[] args) {
  // 闭包
  
  int a=10;
   Consumer<Integer> c=ele->{
   
    System.out.println(a);
    
    System.out.println(a+1);    //正确运行 11
    
    //System.out.println(a++);    //报错:Local variable a defined in an enclosing scope must be final or effectively final
    
    //a++;                        //报错:Local variable a defined in an enclosing scope must be final or effectively final  
      
    //这里的变量a必须是final的。不能是一个变量
   };
   
   c.accept(1);
 }
}

可以看到,lambda表达式可以捕获外围作用域中变量的值。在java中,要确保所捕获的值是明确定义的,这里有一个重要的限制。在lambda表达式中,只能引用值不会改变的变量。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值