JDk1.8 Lambda表达式

JDK1.8Lambda表达式

Lambda 表示式的基础语法: java8中引用新的操作符"->" 该操作称为箭 头操作 Lambda 操作符 表达式拆分成两部门

Lambda

左侧:Lambda 表达式的参数列表
右侧 :Lambda表达式中所需执行的功能 即Lambda 体




    
1./** 
 * 语法格式一 无参数,无返回值
 * () -> System.out.println("Hello Lambda!")
 */
    
 @Test
 public void test1() {
    int num = 0;

    Runnable b = new Runnable() {
        @Override
        public void run() {
            System.out.println("hello World" + num);
        }
    };

    System.out.println("-----------");
    Runnable r1 = () -> System.out.println("hello lambda");
    r1.run();
}
2./**
* 语法格式二:
*   有一个参数,并且无返回值
*   (x) -> System.out.println(x)
*/ 
@Test
public void test2() {
    Consumer<String> con = x -> System.out.println(x);
    con.accept("我大河南");
}

3./**   
*语法格式三:若只有一个参数,小括号可以省略不写
*  x -> System.out.println(x)
*/
 @Test
 public void test3() {
    Comparator<Integer> com = (x, y) -> {
        System.out.println("函数式接口");
        return Integer.compare(x, y);
    };
}

4./**  语法格式四:
 *  有两个以上的参数,并有返回值并且lambda体中有多条语句
 *   Comparator<Integer> com = (x, y) -> {
 *             System.out.println("函数式接口");
 *             return Integer.compare(x,y);
 *         };
 */
@Test
public void test4() {
    Comparator<Integer> com1 = (x, y) -> Integer.compare(x, y);

    Comparator<Integer> com = (Integer x, Integer y) -> Integer.compare(x, y);
}

5./**  语法格式五:若Lambda体中只有一条语句,return 和大括号都可以省略不写
 *   Comparator<Integer> com =(Integer x,Integer y) ->       *Integer.compare(x,y);
 *   语法格式六:Lambda 表达式的参数列表的数据类型可以省略不写,因为
 *   JVm编译器通过上下文推断出,数据类型,即"类型推断"
 */
@Test
public void test5() {
    //   String[] strs ={"aaa","bbb","sss"};
    ArrayList<String> list = new ArrayList<>();
    show(new HashMap<>());
}

public void show(Map<String, Integer> map) {

} 

6./**  语法格式五:若Lambda体中只有一条语句,return 和大括号都可以省略不写
 *
 */  
 @Test
  public void test6() {
      Integer num =operation(100,(x) -> x * x);
      System.out.println(num);
      System.out.println(operation(200,(y) -> y + 200));
 }
      //需求:对一个数进行运算
     public Integer operation (Integer num, MyFunction mf){
          return mf.getValue(num);
      }
     //  lambda表达式需要"函数式接口"的支持
    // 函数式接口:接口中只有一个抽象方法,称为函数式接口可以使用注解@FunctionInterfac
@FunctionalInterface
public interface MyFunction {

    public Integer getValue(Integer str);
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值