前提介绍: stream流的目的是简化我们对集合的操作,让我们更加方便的操作集合,但他并不是必须的,即使没有stream,我们依然可以通过 for,if实现相同的功能

stream的基本功能

stream的map()

  1. .map() 是用于元素映射转换的中间操作,常见于对集合中每个元素进行某种处理,然后生成一个新的元素集合。
  2. .map() 基本语法:
    1
    stream.map(element -> someFunction(element))
  3. 简单示例:

    1
    2
    3
    4
    List<String> names = Arrays.asList("Tom", "Jerry", "Spike");
    List<Integer> nameLengths = names.stream()
    .map(String::length)
    .collect(Collectors.toList());

    nameLengths = [3, 5, 5]

  4. 工作中遇见的 .map()

1
2
3
4
5
6
// 前情提示 watchedList 是一个泛型的List
watchedList.stream()
// e相当于一个watchedList里的数据, buildUserBook 是自定义函数,函数会返回一个结果
.map(e -> this.buildUserBook(e, idMap.get(e.getBookId())))
// 将这些结果形成一个新的集合
.collect(Collectors.toList());
1
2
3
4
5
6
7
8
9
10
11
12
13
// 前情提示 userChapterRelationService.getChapterCollectList 会返回一个List<ChapterCollectPO>de 集合
List<ChapterCollectResp> collectBookList = userChapterRelationService.getChapterCollectList(userInfo.getUserId()).stream().map((e) -> {
// 由于 PO是映射数据库的实体类 Resp是返回前端的实体类 ,所以第一步很明确就是拷贝属性,不得不说这一步很高明
ChapterCollectResp collectResp = ChapterCollectResp.copy(e);
//MybatisPlus的查询 其实这几步相当于自定义方法并返回一个结果了
BookInfoPO bookInfoPO = bookInfoService.lambdaQuery().eq(BookInfoPO::getBookId, e.getBookId()).one();
if (bookInfoPO != null) {
collectResp.setTitle(bookInfoPO.getTitle());
collectResp.setAllNum(bookInfoPO.getAllNum());
collectResp.setFontUrl(bookInfoPO.getFontUrl());
}
return collectResp;
}).collect(Collectors.toList());