Marvel-Site Marvel-Site
首页
  • Java

    • Java基础
    • Java进阶
    • Java容器
    • Java并发编程
    • Java虚拟机
  • 计算机基础

    • 数据结构与算法
    • 计算机网络
    • 操作系统
    • Linux
  • 框架|中间件

    • Spring
    • MySQL
    • Redis
    • MQ
    • Zookeeper
    • Git
  • 架构

    • 分布式
    • 高并发
    • 高可用
    • 架构
  • 框架

    • React
    • 其他
  • 实用工具
  • 安装配置

    • Linux
    • Windows
    • Mac
  • 开发工具

    • IDEA
    • VsCode
  • 关于
  • 收藏
  • 草稿
  • 索引

    • 分类
    • 标签
    • 归档
GitHub (opens new window)

Marvel

吾必当乘此羽葆盖车
首页
  • Java

    • Java基础
    • Java进阶
    • Java容器
    • Java并发编程
    • Java虚拟机
  • 计算机基础

    • 数据结构与算法
    • 计算机网络
    • 操作系统
    • Linux
  • 框架|中间件

    • Spring
    • MySQL
    • Redis
    • MQ
    • Zookeeper
    • Git
  • 架构

    • 分布式
    • 高并发
    • 高可用
    • 架构
  • 框架

    • React
    • 其他
  • 实用工具
  • 安装配置

    • Linux
    • Windows
    • Mac
  • 开发工具

    • IDEA
    • VsCode
  • 关于
  • 收藏
  • 草稿
  • 索引

    • 分类
    • 标签
    • 归档
GitHub (opens new window)
  • Java

    • Java基础

      • Java基本概念与常识
      • Java基本语法
      • Java基本数据类型
      • Java包装类
      • Java基本概念对比辨析
      • Java面向对象基础
      • Java异常处理
      • Java注解
      • Java泛型
      • Java反射
      • Java函数式编程
        • 函数式编程思想
        • Lambda表达式
          • 概念
          • 举例
        • Stream流
          • 概述
          • 案例数据准备
          • 快速入门
          • 常用操作
          • 创建流
          • 中间操作
          • 终结操作
          • 注意事项
          • 常用
        • Optional
          • Optional概述
          • Optional使用
          • 创建对象
          • 安全消费值
          • 获取值
          • 安全获取值
          • 过滤
          • 判断
          • 数据转换
        • 函数式接口
          • 函数式接口概述
          • 常见函数式接口
          • 常用的默认方法
        • 方法引用
          • 引用类的静态方法
          • 引用对象的实例方法
          • 引用类的实例方法
          • 构造器引用
    • Java进阶

    • Java容器

    • Java并发编程

    • Java虚拟机

    • 常见面试题

  • 计算机基础

  • 框架|中间件

  • 架构

  • 后端
  • Java
  • Java基础
Marvel
2023-09-12
目录

Java函数式编程

# Java函数式编程

# 函数式编程思想

概念

面向对象思想需要关注用什么对象完成什么事情。而函数式编程思想就类似于我们数学中的函数。它主要关注的是对数据进行了什么操作。

优点

  1. 代码简洁,开发快速
  2. 接近自然语言,易于理解
  3. 易于"并发编程"

# Lambda表达式

# 概念

Lambda是JDK8中的语法糖,它可以对某些匿名内部类的写法进行简化。它是函数式编程思想的一个重要体现。让我们不用关注是什么对象,而是更关注我们对数据进行了什么操作。关注的是参数列表和具体的逻辑代码体

省略规则:

  • 参数类型可以省略
  • 方法体中只有一句代码时大括号return和唯一一句代码的分号可以省略
  • 方法只有一个参数时小括号可以省略0.

基本格式:

(参数列表)->{代码}
1

# 举例

案例1

正常方法

new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println("test");
    }
}).start();
1
2
3
4
5
6

使用Lambda表达式

new Thread(() -> {
    System.out.println("test");
}).start();
1
2
3

匿名内部类可以使用Lambda表达式进行简化的条件是:这个接口的抽象方法只有一个。

案例2

public static void main(String[] args) {
	// 匿名内部类实现
    int i = calculateNum(new IntBinaryOperator() {
        @Override
        public int applyAsInt(int left, int right) {
            return left + right;
        }
    });
    System.out.println(i);
	
	// lambda表达式
    int j = calculateNum((a, b) -> {
        return a + b;
    });
    System.out.println(j);
}


public static int calculateNum(IntBinaryOperator operator) {
    int a = 10;
    int b = 20;
    return operator.applyAsInt(a, b);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

案例3

public static void main(String[] args) {
    // 打印偶数
    
    // 普通方法
    printNum(new IntPredicate() {
        @Override
        public boolean test(int value) {
            return value % 2 == 0;
        }
    });
    
    // lambda表达
    printNum(value -> {
        return value % 2 == 0;
    });
    
    // 再简化
    printNum(value -> value % 2 == );
    
}


public static void printNum(IntPredicate predicate) {
    int[] arr = {1,2,3,4,5,6,7,8,9,10};
    for (int i : arr) {
        if (predicate.test(i)) {
            System.out.println(i);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

案例4

@FunctionalInterface表示这是个函数式接口,方法apply传入变量参数类型为T,返回参数类型为R。

@FunctionalInterface
public interface Function<T, R> {

    R apply(T t);
	...
}
1
2
3
4
5
6

String类型转为Integer类型

public static void main(String[] args) {
    // 把字符串转换为int类型

    // 普通方法
    Integer num = typeConvert(new Function<String, Integer>() {
        @Override
        public Integer apply(String s) {
            return Integer.parseInt(s);
        }
    });
    System.out.println(num);
    
    // lambda表达式
    Integer num2 = typeConvert(s -> {
        return Integer.parseInt(s);
    });
    System.out.println(num2);
    
    // 再简化
    Integer num3 = typeConvert(Integer::parseInt);
    System.out.println(num3);
    
}


public static <R> R typeConvert(Function<String, R> function) {
    String str = "1235";
    return function.apply(str);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

案例5

public static void main(String[] args) {

    // 普通方法
    foreachArr(new IntConsumer() {
        @Override
        public void accept(int value) {
            System.out.println(value);
        }
    });

    // 使用lambda表达式
    foreachArr((value) -> {
        System.out.println(value);
    });

    // 再简化
    foreachArr(System.out::println);
}


public static void foreachArr(IntConsumer consumer) {
    int[] arr = {1,2,3,4,5,6,7,8,9};
    for (int i : arr) {
        consumer.accept(i);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

# Stream流

# 概述

Java8的Stream使用的是函数式编程模式,如同它的名字一样, 它可以被用来对集合或数组进行链状流式的操作。可以更方便的让我们对集合或数组操作。

# 案例数据准备

@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class Author {
    private Long id;
    private String name;
    private Integer age;
    private String intro;
    private List<Book> books;
}
1
2
3
4
5
6
7
8
9
10
11
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class Book {
    private Long id;
    private String name;
    private String category;
    private Integer score;
    private String info;
}
1
2
3
4
5
6
7
8
9
10
11
private static List<Author> getAuthors() {
    //数据初始化
    Author author = new Author(1L,"蒙多",33,"一个从菜刀中明悟哲理的祖安人",null);
    Author author2 = new Author(2L,"亚拉索",15,"狂风也追逐不上他的思考速度",null);
    Author author3 = new Author(3L,"易",14,"是这个世界在限制他的思维",null);
    Author author4 = new Author(3L,"易",14,"是这个世界在限制他的思维",null);

    //书籍列表
    List<Book> books1 = new ArrayList<>();
    List<Book> books2 = new ArrayList<>();
    List<Book> books3 = new ArrayList<>();

    books1.add(new Book(1L,"刀的两侧是光明与黑暗","哲学,爱情",88,"用一把刀划分了爱恨"));
    books1.add(new Book(2L,"一个人不能死在同一把刀下","个人成长,爱情",99,"讲述如何从失败中明悟真理"));

    books2.add(new Book(3L,"那风吹不到的地方","哲学",85,"带你用思维去领略世界的尽头"));
    books2.add(new Book(3L,"那风吹不到的地方","哲学",85,"带你用思维去领略世界的尽头"));
    books2.add(new Book(4L,"吹或不吹","爱情,个人传记",56,"一个哲学家的恋爱观注定很难把他所在的时代理解"));

    books3.add(new Book(5L,"你的剑就是我的剑","爱情",56,"无法想象一个武者能对他的伴侣这么的宽容"));
    books3.add(new Book(6L,"风与剑","个人传记",100,"两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?"));
    books3.add(new Book(6L,"风与剑","个人传记",100,"两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?"));

    author.setBooks(books1);
    author2.setBooks(books2);
    author3.setBooks(books3);
    author4.setBooks(books3);

    List<Author> authorList = new ArrayList<>(Arrays.asList(author,author2,author3,author4));
    return authorList;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

# 快速入门

需求

我们可以调用getAuthors方法获取到作家的集合。现在需要打印所有年龄小于18的作家的名字,并且要注意去重。

实现

authors.stream():把集合转换成流,返回的就是Stream对象。 .distinct():去重,去除重复项 .filter():过滤,根据条件进行筛选 .forEach():对结果进行遍历处理。

public static void main(String[] args) {
    List<Author> authors = getAuthors();
    authors.stream() // 把集合转换为流
        .distinct() // 去重
        .filter(author -> author.getAge() < 18) // 年龄小于18
        .forEach(author -> System.out.println(author.getName()));
}
1
2
3
4
5
6
7

打断点,进行调试:

img

# 常用操作

# 创建流

单列集合: 集合对象.stream()

List<Author> authors = getAuthors();
Stream<Author> stream = authors.stream();
1
2

数组:Arrays.stream(数组)或者使用Stream.of来创建

Integer[] arr = {1,2,3,4,5};
Stream<Integer> stream = Arrays.stream(arr);
Stream<Integer> stream2 = Stream.of(arr);
1
2
3

双列集合:转换成单列集合后再创建

Map<String,Integer> map = new HashMap<>();
map.put("蜡笔小新",19);
map.put("黑子",17);
map.put("日向翔阳",16);

Stream<Map.Entry<String, Integer>> stream = map.entrySet().stream();
1
2
3
4
5
6

# 中间操作

方法 用法
filter 可以对流中的元素进行条件过滤,符合过滤条件的才能继续留在流中。
map 可以把对流中的元素进行计算或转换。
distinct 可以去除流中的重复元素。
sorted 可以对流中的元素进行排序。
limit 可以设置流的最大长度,超出的部分将被抛弃。
skip 跳过流中的前n个元素,返回剩下的元素。
flatMap 可以把一个对象转换成多个对象作为流中的元素。

filter:可以对流中的元素进行条件过滤,符合过滤条件的才能继续留在流中。

.filter(author -> author.getName().length()>1)
1

map:可以把对流中的元素进行计算或转换。

.map(author -> author.getName())

.map(age->age+10)
1
2
3

distinct:可以去除流中的重复元素

注意:distinct方法是依赖Object的equals方法来判断是否是相同对象的。所以需要注意重写equals方法。

sorted:可以对流中的元素进行排序

.sorted((o1, o2) -> o2.getAge()-o1.getAge())
1

注意:如果调用空参的sorted()方法,需要流中的元素是实现了Comparable。

limit:可以设置流的最大长度,超出的部分将被抛弃。

.limit(2) 最大长度为2
1

skip:跳过流中的前n个元素,返回剩下的元素

.skip(1) //跳过第一个元素
1

flatMap:map只能把一个对象转换成另一个对象来作为流中的元素。而flatMap可以把一个对象转换成多个对象作为流中的元素。

举例1:

打印所有书籍的名字,要求对重复的元素进行去重。

public static void main(String[] args) {
    List<Author> authors = getAuthors();
    // 打印所有书籍的名字。要求对重复的元素进行去重。
    authors.stream()
            .flatMap(author -> author.getBooks().stream())
            .distinct()
            .forEach(book -> System.out.println(book.getName()));
}
1
2
3
4
5
6
7
8

每一个author里包含一个book集合,通过flatMap将多个book集合映射到同一个流当中。

image-20230912202645156

举例2:

打印现有数据的所有分类。要求对分类进行去重。不能出现这种格式:“哲学,爱情”

public static void main(String[] args) {
    List<Author> authors = getAuthors();
    // 打印所有书籍的名字。要求对重复的元素进行去重。
    authors.stream()
            .flatMap(author -> author.getBooks().stream())
            .distinct()
            .flatMap(book -> Arrays.stream(book.getCategory().split(",")))
            .distinct()
            .forEach(System.out::println);
}
1
2
3
4
5
6
7
8
9
10

# 终结操作

方法 用法
forEach 对流中的元素进行遍历操作,我们通过传入的参数去指定对遍历到的元素进行什么具体操作。
count 可以用来获取当前流中元素的个数。
max&min 可以用来或者流中的最值。
collect 把当前流转换成一个集合。
anyMatch 可以用来判断是否有任意符合匹配条件的元素,结果为boolean类型。
allMatch 可以用来判断是否都符合匹配条件,结果为boolean类型。如果都符合结果为true,否则结果为false。
noneMatch 可以判断流中的元素是否都不符合匹配条件。如果都不符合结果为true,否则结果为false。
findAny 获取流中的任意一个元素。该方法没有办法保证获取的一定是流中的第一个元素。
findFirst 获取流中的第一个元素。
reduce 归并

forEach:对流中的元素进行遍历操作,我们通过传入的参数去指定对遍历到的元素进行什么具体操作。

// 输出所有作家的名字
List<Author> authors = getAuthors();

authors.stream()
        .map(author -> author.getName())
        .distinct()
        .forEach(name-> System.out.println(name));
1
2
3
4
5
6
7

count:可以用来获取当前流中元素的个数。

// 打印这些作家的所出书籍的数目,注意删除重复元素。
List<Author> authors = getAuthors();

long count = authors.stream()
        .flatMap(author -> author.getBooks().stream())
        .distinct()
        .count();
System.out.println(count);
1
2
3
4
5
6
7
8

max&min:可以用来或者流中的最值。

// 分别获取这些作家的所出书籍的最高分和最低分并打印。
// Stream<Author>  -> Stream<Book> ->Stream<Integer>  ->  求值

List<Author> authors = getAuthors();
Optional<Integer> max = authors.stream()
        .flatMap(author -> author.getBooks().stream())
        .map(book -> book.getScore())
        .max((score1, score2) -> score1 - score2);

Optional<Integer> min = authors.stream()
        .flatMap(author -> author.getBooks().stream())
        .map(book -> book.getScore())
        .min((score1, score2) -> score1 - score2);
        
System.out.println(max.get());
System.out.println(min.get());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

collect:把当前流转换成一个集合。

// 获取一个存放所有作者名字的List集合。
List<Author> authors = getAuthors();
List<String> nameList = authors.stream()
        .map(author -> author.getName())
        .collect(Collectors.toList());
System.out.println(nameList);
1
2
3
4
5
6
// 获取一个所有书名的Set集合。
List<Author> authors = getAuthors();
Set<Book> books = authors.stream()
        .flatMap(author -> author.getBooks().stream())
        .collect(Collectors.toSet());

System.out.println(books);
1
2
3
4
5
6
7
// 获取一个Map集合,map的key为作者名,value为List<Book>
List<Author> authors = getAuthors();
Map<String, List<Book>> map = authors.stream()
        .distinct()
        .collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));

System.out.println(map);
1
2
3
4
5
6
7

anyMatch:可以用来判断是否有任意符合匹配条件的元素,结果为boolean类型。

// 判断是否有年龄在29以上的作家
List<Author> authors = getAuthors();
boolean flag = authors.stream()
        .anyMatch(author -> author.getAge() > 29);
System.out.println(flag);
1
2
3
4
5

allMatch:可以用来判断是否都符合匹配条件,结果为boolean类型。如果都符合结果为true,否则结果为false。

// 判断是否所有的作家都是成年人
List<Author> authors = getAuthors();
boolean flag = authors.stream()
       .allMatch(author -> author.getAge() >= 18);
System.out.println(flag);
1
2
3
4
5

noneMatch:可以判断流中的元素是否都不符合匹配条件。如果都不符合结果为true,否则结果为false。

// 判断作家是否都没有超过100岁的。
List<Author> authors = getAuthors();

boolean b = authors.stream()
        .noneMatch(author -> author.getAge() > 100);

System.out.println(b);
1
2
3
4
5
6
7

findAny:获取流中的任意一个元素。该方法没有办法保证获取的一定是流中的第一个元素。

// 获取任意一个年龄大于18的作家,如果存在就输出他的名字
List<Author> authors = getAuthors();
Optional<Author> optionalAuthor = authors.stream()
        .filter(author -> author.getAge()>18)
        .findAny();

optionalAuthor.ifPresent(author -> System.out.println(author.getName()));
1
2
3
4
5
6
7

findFirst:获取流中的第一个元素。

//        获取一个年龄最小的作家,并输出他的姓名。
List<Author> authors = getAuthors();
Optional<Author> first = authors.stream()
        .sorted((o1, o2) -> o1.getAge() - o2.getAge())
        .findFirst();

first.ifPresent(author -> System.out.println(author.getName()));
1
2
3
4
5
6
7

reduce:归并

对流中的数据按照你指定的计算方式计算出一个结果。(缩减操作)

reduce的作用是把stream中的元素给组合起来,我们可以传入一个初始值,它会按照我们的计算方式依次拿流中的元素和初始化值进行计算,计算结果再和后面的元素计算。

reduce两个参数的重载形式内部的计算方式如下:

T result = identity;
for (T element : this stream)
	result = accumulator.apply(result, element)
return result;
1
2
3
4

其中identity就是我们可以通过方法参数传入的初始值,accumulator的apply具体进行什么计算也是我们通过方法参数来确定的。

举例:

// 使用reduce求所有作者年龄的和
List<Author> authors = getAuthors();
Integer sum = authors.stream()
        .distinct()
        .map(author -> author.getAge())
        .reduce(0, (result, element) -> result + element);
System.out.println(sum);
1
2
3
4
5
6
7
// 使用reduce求所有作者中年龄的最大值
List<Author> authors = getAuthors();
Integer max = authors.stream()
        .map(author -> author.getAge())
        .reduce(Integer.MIN_VALUE, (result, element) -> result < element ? element : result);

System.out.println(max);
1
2
3
4
5
6
7
// 使用reduce求所有作者中年龄的最小值
List<Author> authors = getAuthors();
Integer min = authors.stream()
        .map(author -> author.getAge())
        .reduce(Integer.MAX_VALUE, (result, element) -> result > element ? element : result);
System.out.println(min);
1
2
3
4
5
6

reduce由三种参数形式:

Optional<T> reduce(BinaryOperator<T> accumulator);
T reduce(T identity, BinaryOperator<T> accumulator);
<U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner);
1
2
3

我们公共使用的是带有两个参数的形式,下面看一下一个参数的重载形式内部的计算

boolean foundAny = false;
T result = null;   // 初始是null,两个参数的时候,初始值是我们定义的
for (T element : this stream) {
    if (!foundAny) {  // 流当中的第一个元素设置为result
        foundAny = true;
        result = element;
    }
    else
        result = accumulator.apply(result, element); // 剩下的部分一样。
}
return foundAny ? Optional.of(result) : Optional.empty(); // 结果封装为Optional返回
1
2
3
4
5
6
7
8
9
10
11

如果用一个参数的重载方法去求最小值代码如下:

// 使用reduce求所有作者中年龄的最小值
List<Author> authors = getAuthors();
Optional<Integer> minOptional = authors.stream()
        .map(author -> author.getAge())
        .reduce((result, element) -> result > element ? element : result);
minOptional.ifPresent(age-> System.out.println(age));
1
2
3
4
5
6

# 注意事项

  • 惰性求值(如果没有终结操作,没有中间操作是不会得到执行的)
  • 流是一次性的(一旦一个流对象经过一个终结操作后。这个流就不能再被使用)
  • 不会影响原数据(我们在流中可以多数据做很多处理。但是正常情况下是不会影响原来集合中的元素的。这往往也是我们期望的)

# 常用

数组求和:total = Arrays.stream(arr).sum()

# Optional

# Optional概述

我们在编写代码的时候出现最多的就是空指针异常。所以在很多情况下我们需要做各种非空的判断。

例如:

Author author = getAuthor();
if(author!=null){
    System.out.println(author.getName());
}
1
2
3
4

尤其是对象中的属性还是一个对象的情况下。这种判断会更多。

而过多的判断语句会让我们的代码显得臃肿不堪。

所以在JDK8中引入了Optional,养成使用Optional的习惯后你可以写出更优雅的代码来避免空指针异常。

并且在很多函数式编程相关的API中也都用到了Optional,如果不会使用Optional也会对函数式编程的学习造成影响。

# Optional使用

# 创建对象

Optional就好像是包装类,可以把我们的具体数据封装Optional对象内部。然后我们去使用Optional中封装好的方法操作封装进去的数据就可以非常优雅的避免空指针异常。

我们一般使用Optional的静态方法ofNullable来把数据封装成一个Optional对象。无论传入的参数是否为null都不会出现问题。

Author author = getAuthor();
Optional<Author> authorOptional = Optional.ofNullable(author);
authorOptional.ifPresent(author1 -> author1.getName());
1
2
3

你可能会觉得还要加一行代码来封装数据比较麻烦。但是如果改造下getAuthor方法,让其的返回值就是封装好的Optional的话,我们在使用时就会方便很多。

而且在实际开发中我们的数据很多是从数据库获取的。Mybatis从3.5版本可以也已经支持Optional了。我们可以直接把dao方法的返回值类型定义成Optional类型,MyBastis会自己把数据封装成Optional对象返回。封装的过程也不需要我们自己操作。

如果你确定一个对象不是空的则可以使用Optional的静态方法of来把数据封装成Optional对象。

Author author = new Author();
Optional<Author> authorOptional = Optional.of(author);
1
2

但是一定要注意,如果使用of的时候传入的参数必须不为null。

如果一个方法的返回值类型是Optional类型。而如果我们经判断发现某次计算得到的返回值为null,这个时候就需要把null封装成Optional对象返回。这时则可以使用Optional的静态方法empty来进行封装。

public static Optional<Author> getAuthorOptional() {
    Author author = ...;
    return author == null ? Optional.empty() : author;
}
1
2
3
4

其实ofNullable方法也是在内部调用了of和empty方法:

public static <T> Optional<T> ofNullable(T value) {
    return value == null ? empty() : of(value);
}
1
2
3

所以,一般使用ofNullable方法。

# 安全消费值

我们获取到一个Optional对象后肯定需要对其中的数据进行使用。这时候我们可以使用其ifPresent方法对来消费其中的值。

这个方法会判断其内封装的数据是否为空,不为空时才会执行具体的消费代码。这样使用起来就更加安全了。

例如,以下写法就优雅的避免了空指针异常。

Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
authorOptional.ifPresent(author -> System.out.println(author.getName()));
1
2

# 获取值

如果我们想获取值自己进行处理可以使用get方法获取,但是不推荐。 因为当Optional内部的数据为空的时候会出现异常。

# 安全获取值

如果我们期望安全的获取值。我们不推荐使用get方法,而是使用Optional提供的以下方法。

orElseGet:获取数据并且设置数据为空时的默认值。如果数据不为空就能获取到该数据。如果为空则根据你传入的参数来创建对象作为默认值返回。

Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
Author author1 = authorOptional.orElseGet(() -> new Author());
1
2

orElseThrow:获取数据,如果数据不为空就能获取到该数据。如果为空则根据你传入的参数来创建异常抛出。

Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
try {
    Author author = authorOptional.orElseThrow((Supplier<Throwable>) () -> new RuntimeException("author为空"));
    System.out.println(author.getName());
} catch (Throwable throwable) {
    throwable.printStackTrace();
}
1
2
3
4
5
6
7

# 过滤

我们可以使用filter方法对数据进行过滤。如果原本是有数据的,但是不符合判断,也会变成一个无数据的Optional对象。

Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
authorOptional.filter(author -> author.getAge()>100).ifPresent(author -> System.out.println(author.getName()));
1
2

# 判断

我们可以使用isPresent方法进行是否存在数据的判断。如果为空返回值为false,如果不为空,返回值为true。但是这种方式并不能体现Optional的好处,更推荐使用ifPresent方法。

Optional<Author> authorOptional = Optional.ofNullable(getAuthor());

if (authorOptional.isPresent()) {
    System.out.println(authorOptional.get().getName());
}
1
2
3
4
5

# 数据转换

Optional还提供了map可以让我们的对数据进行转换,并且转换得到的数据也还是被Optional包装好的,保证了我们的使用安全。

例如我们想获取作家的书籍集合。

private static void testMap() {
    Optional<Author> authorOptional = getAuthorOptional();
    Optional<List<Book>> optionalBooks = authorOptional.map(author -> author.getBooks());
    optionalBooks.ifPresent(books -> System.out.println(books));
}
1
2
3
4
5

# 函数式接口

# 函数式接口概述

只有一个抽象方法的接口我们称之为函数接口。

JDK的函数式接口都加上了@FunctionalInterface注解进行标识。但是无论是否加上该注解只要接口中只有一个抽象方法,都是函数式接口。

# 常见函数式接口

Consumer 消费接口:

根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数进行消费。

@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);
    ...
}
1
2
3
4
5
6
7
8
9
10
11

Function 计算转换接口

根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数计算或转换,把结果返回

@FunctionalInterface
public interface Function<T, R> {

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);
    ...
}
1
2
3
4
5
6
7
8
9
10
11
12

Predicate 判断接口

根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数条件判断,返回判断结果

@FunctionalInterface
public interface Predicate<T> {

    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);
	...
}
1
2
3
4
5
6
7
8
9
10
11
12
13

Supplier 生产型接口

根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中创建对象,把创建好的对象返回

@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}
1
2
3
4
5
6
7
8
9
10

# 常用的默认方法

and:我们在使用Predicate接口时候可能需要进行判断条件的拼接。而and方法相当于是使用&&来拼接两个判断条件。

例如:打印作家中年龄大于17并且姓名的长度大于1的作家。

public static void main(String[] args) {
    List<Author> authors = getAuthors();
    authors.stream()
            .filter(new Predicate<Author>() {
                @Override
                public boolean test(Author author) {
                    return author.getAge() > 17;
                }
            }.and(new Predicate<Author>() {
                @Override
                public boolean test(Author author) {
                    return author.getName().length() > 1;
                }
            }))
            .forEach(author -> System.out.println(author.getName()));
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

使用lambda表达式简化:

public static void main(String[] args) {
    List<Author> authors = getAuthors();
    authors.stream()
            .filter(((Predicate<Author>) author -> author.getAge() > 17).and(author -> author.getName().length() > 1))
            .forEach(author -> System.out.println(author.getName()));
}
1
2
3
4
5
6

or:我们在使用Predicate接口时候可能需要进行判断条件的拼接。而or方法相当于是使用||来拼接两个判断条件。

例如:打印作家中年龄大于17或者姓名的长度小于2的作家。

List<Author> authors = getAuthors();
authors.stream()
    .filter(new Predicate<Author>() {
        @Override
        public boolean test(Author author) {
            return author.getAge()>17;
        }
    }.or(new Predicate<Author>() {
        @Override
        public boolean test(Author author) {
            return author.getName().length()<2;
        }
    })).forEach(author -> System.out.println(author.getName()));
1
2
3
4
5
6
7
8
9
10
11
12
13

negate:Predicate接口中的方法。negate方法相当于是在判断添加前面加了个!表示取反

例如:打印作家中年龄不大于17的作家。

List<Author> authors = getAuthors();
authors.stream()
    .filter(new Predicate<Author>() {
        @Override
        public boolean test(Author author) {
            return author.getAge()>17;
        }
    }.negate()).forEach(author -> System.out.println(author.getAge()));
1
2
3
4
5
6
7
8

# 方法引用

我们在使用lambda时,如果方法体中只有一个方法的调用的话(包括构造方法),我们可以用方法引用进一步简化代码。

基本格式:类名或者对象名::方法名

# 引用类的静态方法

类名::方法名

如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了某个类的静态方法,并且我们把要重写的抽象方法中所有的参数都按照顺序传入了这个静态方法中,这个时候我们就可以引用类的静态方法。

# 引用对象的实例方法

对象名::方法名

如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了某个对象的成员方法,并且我们把要重写的抽象方法中所有的参数都按照顺序传入了这个成员方法中,这个时候我们就可以引用对象的实例方法。

# 引用类的实例方法

类名::方法名

如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了第一个参数的成员方法,并且我们把要重写的抽象方法中剩余的所有的参数都按照顺序传入了这个成员方法中,这个时候我们就可以引用类的实例方法。

# 构造器引用

如果方法体中的一行代码是构造器的话就可以使用构造器引用。

类名::new

如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了某个类的构造方法,并且我们把要重写的抽象方法中的所有的参数都按照顺序传入了这个构造方法中,这个时候我们就可以引用构造器。

编辑 (opens new window)
#后端#Java
上次更新: 2024/04/17, 21:30:18
Java反射
类的初始化与对象的初始化

← Java反射 类的初始化与对象的初始化→

最近更新
01
位运算
05-21
02
二叉树
05-12
03
Spring三级缓存解决循环依赖
03-25
更多文章>
Theme by Vdoing | Copyright © 2022-2024 Marvel
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式