Home
  • 计算机网络
  • 操作系统
  • 数据结构与算法
  • 设计模式
  • JavaSE
  • JVM
  • JUC
  • Netty
  • CPP
  • QT
  • UE
  • Go
  • Gin
  • Gorm
  • HTML
  • CSS
  • JavaScript
  • vue2
  • TypeScript
  • vue3
  • react
  • Spring
  • SpringMVC
  • Mybatis
  • SpringBoot
  • SpringSecurity
  • SpringCloud
  • Mysql
  • Redis
  • 消息中间件
  • RPC
  • 分布式锁
  • 分布式事务
  • 个人博客
  • 弹幕视频平台
  • API网关
  • 售票系统
  • 消息推送平台
  • SaaS短链接系统
  • Linux
  • Docker
  • Git
GitHub (opens new window)
Home
  • 计算机网络
  • 操作系统
  • 数据结构与算法
  • 设计模式
  • JavaSE
  • JVM
  • JUC
  • Netty
  • CPP
  • QT
  • UE
  • Go
  • Gin
  • Gorm
  • HTML
  • CSS
  • JavaScript
  • vue2
  • TypeScript
  • vue3
  • react
  • Spring
  • SpringMVC
  • Mybatis
  • SpringBoot
  • SpringSecurity
  • SpringCloud
  • Mysql
  • Redis
  • 消息中间件
  • RPC
  • 分布式锁
  • 分布式事务
  • 个人博客
  • 弹幕视频平台
  • API网关
  • 售票系统
  • 消息推送平台
  • SaaS短链接系统
  • Linux
  • Docker
  • Git
GitHub (opens new window)
  • Java语法

  • Java容器

  • Java新特性

    • Java8

      • 函数式接口
        • 什么是函数式接口?
        • Function
        • Consumer
        • Supplier
      • 方法引用
      • Stream流
      • Lambda表达式
  • IDEA常用快捷键
  • 正则表达式
  • API
  • 场景题

  • JavaSE
  • Java新特性
  • Java8
Nreal
2023-12-05
目录

函数式接口

# 什么是函数式接口?

  1. 单一抽象方法:函数式接口包含一个抽象方法;
  2. @FunctionalInterface:标识一个接口为函数式接口;
  3. 可使用Lambda表达式创建函数式接口的实例,实现接口的抽象方法;
  4. 函数式接口可以包含default方法和static方法,默认方法提供了一种为接口添加新方法而不破坏现有实现的机制;
  5. 通用函数接口:Java标准库中有一些通用的函数式接口,如Function、Consumer、Supplier、Predicate等;

# Function

用于将一个值转换为另一个值;

定义了一个接受一个参数并返回结果的函数;

@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);
}
1
2
3
4

T表示输入参数类型,R表示返回结果类型;

案例:将字符串转换为大写;

public class FunctionTest {
    public static void main(String[] args) {
        Function<String,String> uppercaseFunction = str->str.toUpperCase();
        String res = uppercaseFunction.apply("rui");
        System.out.println(res);
    }
}
1
2
3
4
5
6
7

# Consumer

接受一个参数,没有返回值;

@FunctionalInterface
public interface Consumer<T> {
    void accept(T arg0);
}
1
2
3
4

案例:打印名字;

public class ConsumerTest {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("rui", "kk");
        Consumer<String> printName = name-> System.out.println(name);
        list.forEach(printName);
    }
}
1
2
3
4
5
6
7

# Supplier

不接受参数,对外提供返回值;

@FunctionalInterface
public interface Supplier<T> {
    T get();
}
1
2
3
4

案例:提供一个随机数;

public class SupplierTest {
    public static void main(String[] args) {
        Supplier<Integer> randomNumSupplier = ()->new Random().nextInt();
        int randomNum = randomNumSupplier.get();
        System.out.println(randomNum);
    }
}
1
2
3
4
5
6
7
其它
方法引用

← 其它 方法引用→

Theme by Vdoing | Copyright © 2021-2024
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式