Lambda表达式的使用

什么是Lambda表达式?

Lambda表达式,也可称为闭包。类似于JavaScript中的闭包,它是推动Java8发布的最重要的新特性。

在哪里使用 Lambda

  • 实现匿名内部类
  • 函数声明与调用

Lambda表达式语法

Lambda表达式有三个部分:

1、参数列表——这里它采用了Comparator中compare方法的参数,两个Apple。

2、箭头——箭头->把参数列表与Lambda主体分隔开。

3、Lambda主体——比较两个Apple的重量。表达式就是Lambda的返回值了。

使用Lambda

函数式接口

为了应用不同的Lambda表达式,我们需要一套能够描述常见函数描述符的函数式接口。Java API中已经有了几个函数式接口,比如Comparator、Runnable,以及Callable。Java 8在java.util.function包中引入了几个新的函数式接口。

什么是函数式接口?

只包含一个抽象方法的接口,就称为函数式接口。==我们可以通过Lambda表达式来创建该接口的实现对象。
我们可以在任意函数式接口上使用@FunctionalInterface注解,这样做可以用于检测它是否是一个函数式接口,同时javadoc也会包含一条声明,说明这个接口是一个函数式接口。

自定义函数式接口

按照函数式接口的定义,自定义一个函数式接口,如下:

// 通知编译器这是函数式接口,进行抽象方法检查
@FunctionalInterface
public interface MathOperation {
    public float operate(Integer a,Integer b);
}

实现函数式接口:

public class LambdaSample {

    public static void main(String[] args) {
        /**
         * 约束条件:Lambda表达式只能实现有且只有一个抽象方法的接口,
         * Java称为"函数式接口"
         *
         * Lambda允许忽略参数类型
         * 单行实现代码可以省略大括号和return
         */

        // 加法运算
        MathOperation multiplication = (Integer a,Integer b)->{
            return a+b+0f;
        };
        System.out.println(multiplication.operate(5,3));

        //减法运算
        MathOperation substraction = (Integer a,Integer b)->{
            return a-b+0f;
        };
        System.out.println(substraction.operate(5,3));
    }

}

JDK8常用函数式接口

 使用示例:

// 常用函数式接口介绍
public class FunctionSample {
    public static void main(String[] args) {
        // Consumer接口的使用
        oupput(s -> System.out.println("向控制台打印:" + s));
        oupput(s -> System.out.println("向xxx网站发送数据包:" + s));

        // Predicate函数式接口的使用方法
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        filter(list,n->n%2==1); //取所有奇数
        filter(list,n->n%2==0); //取所有偶数
        filter(list,n->n>5 && n%2==0); //取所有大于5的偶数

        // 利用Function函数式接口生成定长随机字符串
        randonString(l->{
            String chars = "abcdefghijklmnopqrstuvxwyz0123456789";
            StringBuffer stringBuffer = new StringBuffer();
            Random random = new Random();
            for (int i = 0; i < l; i++) {
                int i1 = random.nextInt(chars.length());
                stringBuffer.append(chars.charAt(i1));
            }
            return stringBuffer.toString();
        },32);
    }

    // Predicate函数式接口的使用方法
    public static void filter(List<Integer> list, Predicate<Integer> predicate){
        for (Integer num:list
             ) {
            if (predicate.test(num)){
                System.out.print(num+" ");
            }
        }
        System.out.println("");
    }

    // Consumer接口的使用
    public static void oupput (Consumer<String> consumer){
        String text = "天将降大任于是人也,必先苦其心志,劳其筋骨,饿其体肤,空乏其身,行拂乱其所为。";
        consumer.accept(text);
    }

    // function接口的使用
    public static void randonString (Function<Integer,String> function,Integer length){
        System.out.println(function.apply(length));
    }

}

Stream流式处理

  • Stream流式处理是建立在Lambda基础上的多数据处理技术
  • Stream对集合数据处理进行高度抽象,极大简化代码量
  • Stream可对集合进行迭代,去重,筛选,排序,聚合等一系列处理

     

需要引入两个jar包

 

 Stream操作实例:

/ Stream流式处理
public class StreamMethod {
    // 提取集合中所有偶数并求和
    @Test
    public void case1(){
        List<String> list = Arrays.asList("1", "2", "3", "4", "5" , "6");
        int sum = list.stream()   //获取stream对象
                .mapToInt(s -> Integer.parseInt(s)) //mapToInt将流中每一个数据转为整数
                .filter(n -> n % 2 == 0)  //filter对流数据进行过滤
                .sum();//求和
        System.out.println(sum);        
    }

    // 所有名字首字母大写
    @Test
    public void case2(){
        List<String> list = Arrays.asList("lily", "smith", "jackson");
        List<String> list1 = list.stream()
                .map(s -> s.substring(0, 1).toUpperCase() + s.substring(1))
                .collect(Collectors.toList());
        System.out.println(list1);
    }

    // 将所有奇数从大到小进行排序,且不允许重复
    @Test
    public void case3(){
        List<Integer> list = Arrays.asList(1, 60, 38, 21, 51, 60, 51, 73);
        List<Integer> list1 = list.stream().distinct()
                .filter(n -> n % 2 == 1)
                .sorted((a, b) -> b - a)
                .collect(Collectors.toList());
        System.out.println(list1);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值