【java8新特性】之lambda表达式

  • lambda表达式作用:1、用于实现简单的接口。2、遍历集合

  • 重要特征如下:

  1. 可选类型声明:不需要声明参数类型,编译器可以统一识别参数值。
  2. 可选的参数圆括号:一个参数无需定义圆括号,但多个参数需要定义圆括号。
  3. 可选的大括号:如果主体包含了一个语句,就不需要使用大括号。
  4. 可选的返回关键字:如果主体只有一个表达式返回值则编译器会自动返回值,大括号需要指定明表达式返回了一个数值。
  • 几种表达式格式
// 1. 不需要参数,返回值为 5  
() -> 5  
  
// 2. 接收一个参数(数字类型),返回其2倍的值  
x -> 2 * x  
  
// 3. 接受2个参数(数字),并返回他们的差值  
(x, y) -> x – y  
  
// 4. 接收2个int型整数,返回他们的和  
(int x, int y) -> x + y  
  
// 5. 接受一个 string 对象,并在控制台打印,不返回任何值(看起来像是返回void)  
(String s) -> System.out.print(s)
  •  举几个栗子:
  • 1、实现接口
  • package com.imooc.demofirst;
    
    /**
     * @Author: tongys
     * @Date: 2019/8/1
     * lambda表达式的作用:用于实现简单的接口方法
     */
    public class LambdaTest {
        public static void main(String args[]){
            AddMath addMath = (a,b)->System.out.println(a+b); //只有一个语句的就不要用大括号包裹
            addMath.getResult(1,2);//结果3
    
            SubMath subMath = (a,b)->{return a-b;};//或者(a,b)->{a-b}
            getSubResult(5,1,subMath);//结果4
        }
    
       interface AddMath{
            void getResult(int a,int b);
        }
        interface SubMath{
            int sub(int a,int b);
        }
        private static void getSubResult(int a,int b,SubMath subMath){
            System.out.println(subMath.sub(a,b));
        }
    }
    
  • 2、遍历集合
  •        //遍历集合
             List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
    	features.stream().forEach(n -> System.out.println(n));//流式
    
            //利用流给集合的每一个元素进行操作
            List<Integer> nums = Arrays.asList(100,200,300,400,500);		 
    	nums.stream().map((num) -> num + num*0.1)
    		 .forEach((num) -> System.out.println("数字增加10%后是:"+num));
            
            //过滤集合
            List<Integer> numList = Arrays.asList(1, 1, null, 2, 3, 4, null, 5, 6, 7, 8, 9, 10);
            numList.stream()
                    .filter(num -> num != null)  //过滤掉是null的元素
                    .forEach(num->System.out.println(num));

     

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值