百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT知识 > 正文

你所不知道的Java8新特性:Lambda表达式和函数式接口

liuian 2025-01-09 14:25 17 浏览

前言

为什么要用Lambda表达式?


Lambda是一个匿名函数,我们可以把Lambda表达式理解为是一段可以传递的代码,将代码像数据一样传递,这样可以写出更简洁、更灵活的代码,作为一个更紧凑的代码风格,使Java语言表达能力得到了提升

实例代码

Lambda表达式最先替代的就是匿名内部类,假设原来我们写一个Comparator比较函数,采用匿名内部类的方式

/**
     * 原来使用匿名内部类
     */
    public static void test() {
        // 使用匿名内部类,重写Intger的 compare方法
        Comparator<Integer> comparator = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return Integer.compare(o1, o2);
            }
        };

        // 传入比较的方法
        TreeSet<Integer> ts = new TreeSet<>(comparator);
    }

然后在采用Lambda表达式后

/**
     * 使用Lambda表达式解决匿名内部类需要编写大量模板语言的问题
     */
    public static void test2() {
        Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y);

        // 传入比较的方法
        TreeSet<Integer> ts = new TreeSet<>(comparator);
    }

策略设计模式

假设我们现在有一个需求,就是查找出员工里面年龄超过35的,我们使用策略设计模式

/**
 * 员工类
 *
 * @author: 陌溪
 * @create: 2020-04-05-12:13
 */
public class Employee {
    private String name;
    private int age;
    private double salary;
    
    // set get
}

然后创建一个接口,这里就是判定条件

/**
 * 接口
 * @param <T>
 */
public interface MyPredicte<T> {
    public boolean test(T t);
}

我们实现这个接口

/**
 * 按年龄过滤
 *
 * @author: 陌溪
 * @create: 2020-04-05-12:23
 */
public class FilterEmployeeByAge implements MyPredicte<Employee> {

    @Override
    public boolean test(Employee employee) {
        return employee.getAge() > 35;
    }
}

然后在具体的例子中使用

/**
     * 获取当前公司员工年龄大于35
     */
    public static void test3() {
        List<Employee> employees = Arrays.asList(
                new Employee("张三", 18, 3333),
                new Employee("李四", 38, 55555),
                new Employee("王五", 50, 6666.66),
                new Employee("赵六", 16, 77777.77),
                new Employee("田七", 8, 8888.88)
        );

        MyPredicte<Employee> mp = new FilterEmployeeByAge();
        List<Employee> emps = new ArrayList<>();
        for (Employee emp : emps) {
            if(mp.test(emp)) {
                emps.add(emp);
            }
        }
    }

当某一天需求变更了,变成需要查找金额大于60000的,那么只需要在编写一个实现类即可

/**
 * 按薪资过滤
 *
 * @author: 轻狂书生FS
 * @create: 2020-10-05-12:23
 */
public class FilterEmployeeBySalary implements MyPredicte<Employee> {

    @Override
    public boolean test(Employee employee) {
        return employee.getSalary() > 60000;
    }
}

那么具体使用只需要更改为

/**
     * 获取当前公司薪资大于60000
     */
    public static void test3() {
        List<Employee> employees = Arrays.asList(
                new Employee("张三", 18, 3333),
                new Employee("李四", 38, 55555),
                new Employee("王五", 50, 6666.66),
                new Employee("赵六", 16, 77777.77),
                new Employee("田七", 8, 8888.88)
        );

        MyPredicte<Employee> mp = new FilterEmployeeBySalary();
        List<Employee> emps = new ArrayList<>();
        for (Employee emp : emps) {
            if(mp.test(emp)) {
                emps.add(emp);
            }
        }
    }

这样一个方法,被称为策略设计模式

匿名内部类

使用上面的策略设计模式,我们会发现一个问题,就是每当我需要增加一个条件的时候,就需要增加一个实现类,如果条件多了的话,那么就会有很多实现类,那么为了优化,我们可以采取匿名内部类的方式

/**
     * 优化方式,采用匿名内部类的方式
     */
    public static void test5() {
        List<Employee> employees = Arrays.asList(
                new Employee("张三", 18, 3333),
                new Employee("李四", 38, 55555),
                new Employee("王五", 50, 6666.66),
                new Employee("赵六", 16, 77777.77),
                new Employee("田七", 8, 8888.88)
        );

        // 匿名内部类
        filterEmployee(employees, new MyPredicte<Employee>() {
            @Override
            public boolean test(Employee employee) {
                return employee.getSalary() <= 5000;
            }
        });
    }

直接在内部类中,使用我们的过滤条件

Lambda表达式

/**
     * 使用Lambda表达式优化
     */
    public static void test6() {
        List<Employee> employees = Arrays.asList(
                new Employee("张三", 18, 3333),
                new Employee("李四", 38, 55555),
                new Employee("王五", 50, 6666.66),
                new Employee("赵六", 16, 77777.77),
                new Employee("田七", 8, 8888.88)
        );

        List<Employee> list = filterEmployee(employees, (e) -> e.getSalary() <= 5000);
        list.forEach(System.out::println);
    }

或者

/**
     * 不使用策略模式
     */
    public static void test7() {
        List<Employee> employees = Arrays.asList(
                new Employee("张三", 18, 3333),
                new Employee("李四", 38, 55555),
                new Employee("王五", 50, 6666.66),
                new Employee("赵六", 16, 77777.77),
                new Employee("田七", 8, 8888.88)
        );
        employees.stream().filter(e-> e.getSalary() >= 5000).limit(2).forEach(System.out::println);
        
        System.out.println("=========");
        employees.stream().map(Employee::getName).forEach(System.out::println);
    }

学习Lambda

Lambda表达式基础语法:Java8中引入了一个新的操作符 “->” 该操作符称为箭头操作符 或 Lambda操作符

箭头操作符将Lambda表达式拆分为两部分:

  • 左侧:Lambda表达式的参数列表(可以想象成,是上面定义的接口中抽象方法参数的列表)
  • 右侧:Lambda表达式中,所需要执行的功能,即Lambda体(需要对抽象方法实现的功能)

语法格式

1、无参,无返回值

格式:

() -> System.out.println(“hello”);

举例:

public static void test() {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                System.out.println("hello");
            }
        };

        System.out.println("=========");

        Runnable runnable = () -> {
            System.out.println("hello lambda");
        };
    }

JDK1.8以后,调用Lambda外的值,不需要增加final字段,它默认已经添加了final

int n = 10;
Runnable runnable = () -> {
	System.out.println("hello lambda" + n);
};

2、有一个参数,有返回值

格式:

(x) -> System.out.println(x);
或  (一个参数时,小括号可以省略不写)
x -> System.out.println(x);

实例:

public static void test2() {
    Consumer<String> consumer = (x) -> System.out.println(x);
    consumer.accept("我在bilibili");
}

3、有多个参数,一个返回值

/**
     * 多个参数,有返回值
     */
    public static void test3() {
        Comparator<Integer> comparator = (x, y) -> {
            System.out.println("函数式接口");
            return Integer.compare(x, y);
        };
    }

4、有多个参数,只有一条语句

这个时候,可以省略大括号 和 return

/**
     * 多个参数,函数体只有一条,并且有返回值时
     */
    public static void test4() {
        Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y);
    }

类型推断

Lambda中,表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型,即“类型推断”。

(Integer x, Integer y) -> Integer.compare(x, y);

但是底层的类型检查还是有的,只是JDK底层帮我们做了类型检查这件事

函数式接口

Lambda表达式需要“函数式接口”的支持

函数式接口:接口中只有一个抽象方法的接口,称为函数式接口,如:

/**
 * 函数式接口 
 */
public interface MyPredicte<T> {
    public boolean test(T t);
}

可以使用注解 @FunctionalInterface 修饰的,则为函数式接口

/**
 * 接口,用于解决重复条件
 * @param <T>
 */
@FunctionalInterface
public interface MyPredicte<T> {
    public boolean test(T t);
}

场景

对一个数进行某种运算

首先创建一个函数式接口

@FunctionalInterface
public interface MyFun {
    public Integer getValue(Integer value);
}

然后在定义一个方法,把方法作为参数传递

/**
     * 需求:对一个数进行运算
     */
    public static void test5() {
        Integer value = operation(100, (x) -> x*x);
        System.out.println(value);
    }

    public static Integer operation(Integer num, MyFun myFun) {
        return myFun.getValue(num);
    }

训练

  • 调用Collections.sort()方法,通过定制排序比较两个Employee(先比较年龄比,年龄相同比较姓名),使用Lambda表达式
public static void test() {
        List<Employee> employees = Arrays.asList(
                new Employee("张三", 18, 3333),
                new Employee("李四", 38, 55555),
                new Employee("王五", 50, 6666.66),
                new Employee("赵六", 16, 77777.77),
                new Employee("田七", 8, 8888.88)
        );
        Collections.sort(employees, (e1, e2) -> {
            if(e1.getAge() == e2.getAge()) {
                return e1.getName().compareTo(e2.getName());
            } else {
                return Integer.compare(e1.getAge(), e2.getAge());
            }
        });

        employees.stream().map(Employee::getName).forEach(System.out::println);
    }

Java内置函数接口

Comsumer 消费型接口

格式:Comsumer<T>

传入参数,然后对参数进行操作,没有返回值

/**
     * 消费型接口
     */
    public static void test() {
        happy(1000, (m) -> System.out.println("消费成功:" + m + "元"));
    }
    public static void happy(double money, Consumer<Double> consumer) {
        consumer.accept(money);
    }

Supplier 供给型接口

格式:Supplier<T>

T get();

传入参数,对参数进行操作,然后有返回值

/**
     * 供给型接口,供给功能如何实现
     */
    public static void test2() {
        List<Integer> list = getNumList(10, () -> {
          Integer a =   (int)(Math.random() * 10);
          return a;
        });

        list.stream().forEach(System.out::println);
    }

    /**
     * 产生指定个数的整数
     * @param n
     * @return
     */
    public static List<Integer> getNumList(Integer n, Supplier<Integer> supplier) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            list.add(supplier.get());
        }
        return list;
    }

最后输出结果

0
5
9
4
4
3
4
5
0
3

Function 函数型接口

格式:Function<T,R>

R apply(T t);

/**
     * 函数型接口
     * Function<T, R>
     */
    public static void test3() {
        String str = strHandler("abcdefg", (x) -> {
            return x.toUpperCase().substring(0, 5);
        });
        System.out.println(str);
    }

    /**
     * 需求:用于处理字符串
     */
    public static String strHandler(String str, Function<String, String> function) {
        // 使用apply方法进行处理,怎么处理需要具体实现
        return function.apply(str);
    }

输出结果:

ABCDE

Predicate 断言型接口

格式:Predicate<T>, 用于做一些判断

/**
     * 断言型接口(把长度大于3的str过滤出来)
     */
    public static void test4() {
        List<String> list = Arrays.asList("abc", "abcd", "df", "cgg", "aaab");
        List<String> result = strPredict(list, (x) -> x.length() > 3);
        result.forEach(item -> {
            System.out.println(item);
        });
    }

    /**
     * 将满足条件的字符串,放入到集合中
     */
    public static List<String> strPredict(List<String> list, Predicate<String> predicate) {
        List<String> result = new ArrayList<>();
        list.forEach(item -> {
            if(predicate.test(item)) {
                result.add(item);
            }
        });
        return result;
    }

扩展

上述的四大核心接口,并不能被适用于一个特殊的应用场景,只能满足大部分的需求

因为他们对于参数的参入有局限性

同时后面针对这样的情况,后面也使用子接口,进行了解决

作者:轻狂书生FS

原文链接:https://blog.csdn.net/LookForDream_/article/details/109157130

相关推荐

2023年最新微信小程序抓包教程(微信小程序 抓包)

声明:本公众号大部分文章来自作者日常学习笔记,部分文章经作者授权及其他公众号白名单转载。未经授权严禁转载。如需转载,请联系开百。请不要利用文章中的相关技术从事非法测试。由此产生的任何不良后果与文...

测试人员必看的软件测试面试文档(软件测试面试怎么说)

前言又到了毕业季,我们将会迎来许多需要面试的小伙伴,在这里呢笔者给从事软件测试的小伙伴准备了一份顶级的面试文档。1、什么是bug?bug由哪些字段(要素)组成?1)将在电脑系统或程序中,隐藏着的...

复活,视频号一键下载,有手就会,长期更新(2023-12-21)

视频号下载的话题,也算是流量密码了。但也是比较麻烦的问题,频频失效不说,使用方法也难以入手。今天,奶酪就来讲讲视频号下载的新方案,更关键的是,它们有手就会有用,最后一个方法万能。实测2023-12-...

新款HTTP代理抓包工具Proxyman(界面美观、功能强大)

不论是普通的前后端开发人员,还是做爬虫、逆向的爬虫工程师和安全逆向工程,必不可少会使用的一种工具就是HTTP抓包工具。说到抓包工具,脱口而出的肯定是浏览器F12开发者调试界面、Charles(青花瓷)...

使用Charles工具对手机进行HTTPS抓包

本次用到的工具:Charles、雷电模拟器。比较常用的抓包工具有fiddler和Charles,今天讲Charles如何对手机端的HTTS包进行抓包。fiddler抓包工具不做讲解,网上有很多fidd...

苹果手机下载 TikTok 旧版本安装包教程

目前苹果手机能在国内免拔卡使用的TikTok版本只有21.1.0版本,而AppStore是高于21.1.0版本,本次教程就是解决如何下载TikTok旧版本安装包。前期准备准备美区...

【0基础学爬虫】爬虫基础之抓包工具的使用

大数据时代,各行各业对数据采集的需求日益增多,网络爬虫的运用也更为广泛,越来越多的人开始学习网络爬虫这项技术,K哥爬虫此前已经推出不少爬虫进阶、逆向相关文章,为实现从易到难全方位覆盖,特设【0基础学爬...

防止应用调试分析IP被扫描加固实战教程

防止应用调试分析IP被扫描加固实战教程一、概述在当今数字化时代,应用程序的安全性已成为开发者关注的焦点。特别是在应用调试过程中,保护应用的网络安全显得尤为重要。为了防止应用调试过程中IP被扫描和潜在的...

一文了解 Telerik Test Studio 测试神器

1.简介TelerikTestStudio(以下称TestStudio)是一个易于使用的自动化测试工具,可用于Web、WPF应用的界面功能测试,也可以用于API测试,以及负载和性能测试。Te...

HLS实战之Wireshark抓包分析(wireshark抓包总结)

0.引言Wireshark(前称Ethereal)是一个网络封包分析软件。网络封包分析软件的功能是撷取网络封包,并尽可能显示出最为详细的网络封包资料。Wireshark使用WinPCAP作为接口,直接...

信息安全之HTTPS协议详解(加密方式、证书原理、中间人攻击 )

HTTPS协议详解(加密方式、证书原理、中间人攻击)HTTPS协议的加密方式有哪些?HTTPS证书的原理是什么?如何防止中间人攻击?一:HTTPS基本介绍:1.HTTPS是什么:HTTPS也是一个...

Fiddler 怎么抓取手机APP:抖音、小程序、小红书数据接口

使用Fiddler抓取移动应用程序(APP)的数据接口需要进行以下步骤:首先,确保手机与计算机连接在同一网络下。在计算机上安装Fiddler工具,并打开它。将手机的代理设置为Fiddler代理。具体方...

python爬虫教程:教你通过 Fiddler 进行手机抓包

今天要说说怎么在我们的手机抓包有时候我们想对请求的数据或者响应的数据进行篡改怎么做呢?我们经常在用的手机手机里面的数据怎么对它抓包呢?那么...接下来就是学习python的正确姿势我们要用到一款强...

Fiddler入门教程全家桶,建议收藏

学习Fiddler工具之前,我们先了解一下Fiddler工具的特点,Fiddler能做什么?如何使用Fidder捕获数据包、修改请求、模拟客户端向服务端发送请求、实施越权的安全性测试等相关知识。本章节...

fiddler如何抓取https请求实现手机抓包(100%成功解决)

一、HTTP协议和HTTPS协议。(1)HTTPS协议=HTTP协议+SSL协议,默认端口:443(2)HTTP协议(HyperTextTransferProtocol):超文本传输协议。默认...