前提介绍: stream流的目的是简化我们对集合的操作,让我们更加方便的操作集合,但他并不是必须的,即使没有stream,我们依然可以通过 for,if实现相同的功能
stream的基本功能
stream的map()
- .map() 是用于元素映射转换的中间操作,常见于对集合中每个元素进行某种处理,然后生成一个新的元素集合。
- .map() 基本语法:
1
| stream.map(element -> someFunction(element))
|
简单示例:
1 2 3 4
| List<String> names = Arrays.asList("Tom", "Jerry", "Spike"); List<Integer> nameLengths = names.stream() .map(String::length) .collect(Collectors.toList());
|
工作中遇见的 .map()
1 2 3 4 5 6
| watchedList.stream() .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
| List<ChapterCollectResp> collectBookList = userChapterRelationService.getChapterCollectList(userInfo.getUserId()).stream().map((e) -> { ChapterCollectResp collectResp = ChapterCollectResp.copy(e); 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());
|