Java8 Stream的各種使用姿勢

Stream簡介

  Java 8 API添加了一個新的抽象稱爲流(Stream),它可以讓你以一種聲明的方式處理數據。這種風格將要處理的元素集合看作一種流,流在管道中傳輸,並且可以在管道的節點上進行處理,比如篩選,排序,聚合等。

概括來說:Stream的出生就是爲了代碼好看、爲了性能高

如何Debug

  在IDEADebug窗口找到Trace Current Stream Chain按鈕,點擊打開就行啦。

Stream常用到的方法

List<TestRes> list = Arrays.asList(
	new TestRes().setId(1L).setSiteId(1L),
	new TestRes().setId(2L).setSiteId(1L),
	new TestRes().setId(3L).setSiteId(2L),
	new TestRes().setId(4L).setSiteId(2L),
	new TestRes().setId(5L).setSiteId(2L),
	new TestRes().setId(6L).setSiteId(2L)
);

// 1. map(), 維度不變, 一一映射
// List<Long> idList = list.stream().map(e -> {
//     return e.getId();
// }).collect(Collectors.toList());
List<Long> idList = list.stream().map(TestRes::getId).collect(Collectors.toList());

// 2. reduce(), 降維處理, 允許默認值
Integer result = Arrays.stream(
    new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9}
).reduce(0, Integer::sum);

// 3. filter(), 過濾器
// List<TestRes> resList = list.stream().filter(e -> {
//     return e.getId() >= 3L;
// }).collect(Collectors.toList());
List<TestRes> resList = list.stream().filter(
    e -> e.getId() >= 3L
).collect(Collectors.toList());

// 4. limit(), 限制流數量
List<TestRes> limitResList = list.stream().limit(3).collect(Collectors.toList());

// 5. count(), 計數
long count = list.stream().filter(Objects::nonNull).count();

// 6. sort(), 排序, 可自定義比較器
List<Integer> sortList = Arrays.stream(
    new Integer[]{9, 8, 7, 6, 5, 4, 3, 2, 1}
).sorted().collect(Collectors.toList());

根據Map的Value排序

Map<Long, TestRes> map = new HashMap<>();
map.put(1L, new TestRes().setId(1L).setHits(3));
map.put(2L, new TestRes().setId(2L).setHits(5));
map.put(3L, new TestRes().setId(3L).setHits(2));
map.put(4L, new TestRes().setId(4L).setHits(4));
map.put(5L, new TestRes().setId(5L).setHits(1));

List<TestRes> sortResult = new ArrayList<>();
map.entrySet().stream().sorted(
    Comparator.comparingInt(o -> o.getValue().getHits())
).forEachOrdered(entry -> {
    sortResult.add(entry.getValue());
});

其他操作:
.distinct() 去重;
.flatMap() 流的扁平化操作;
.forEach() 遍歷, void式操作; .peek() 遍歷, 返回新的流;
.findFirst() 查找第一個滿足條件的元素; .findAny() 查找任一滿足條件的元素
.anyMatch() 有無匹配元素; .allMatch() 是否全部匹配; .noneMatch() 是否無一匹配;
.max() 找最大值, 可自定義比較器; .min() 找最小值, 可自定義比較器;

Stream常用到的收集器

// 1. toList()
// 2. groupingBy()
Map<Long, List<TestRes>> listMap = list.stream().collect(
    Collectors.groupingBy(TestRes::getSiteId, Collectors.toList())
);

// 3. toMap()
Map<Long, TestRes> resMap = list.stream().collect(
    Collectors.toMap(TestRes::getId, Function.identity())
);

// 4. toSet()
Set<String> set = Arrays.stream(
    new String[]{"Java", "Python", "C", "Java"}
).collect(Collectors.toSet());

// 5. joining()
String join = list.stream().map(
    e -> e.getId().toString()
).collect(Collectors.joining(","));

Stream使用時性能隱患注意點

處理N+1查詢

/*************************************************************************
* 【需求:查詢所有站點下的全部資源,並打印所有資源及其所屬站點】
*************************************************************************/
List<Site> sites = siteService.selectByExample(
    Example.builder(Site.class).andWhere(
        Sqls.custom().andIn("id", Arrays.asList(58L, 49L, 76L, 91L, 81L))
    ).build()
);

/******************************** old  ********************************/
long to1 = Instant.now().toEpochMilli();
sites.forEach(site -> {
    List<TestRes> resList = resService.select(
        new TestRes().setSiteId(site.getId())
    );
    resList.forEach(res -> {
        // System.out.println(
        //     String.format("%s, res from ==> %s", res.getName(), site.getName())
        // );
    });
});
log.info("old method complete in ==> {}", Instant.now().toEpochMilli() - to1);
// old method complete in ==> 627

/******************************** new  ********************************/
long tn1 = Instant.now().toEpochMilli();
// 批量查詢所有資源
List<Long> siteIds = fors.stream().map(Site::getId).collect(Collectors.toList());
List<TestRes> resList = resService.selectByExample(
    Example.builder(TestRes.class).andWhere(Sqls.custom().andIn("siteId", siteIds)).build()
);

// 構造站點映射集
Map<Long, Site> siteMap = sites.stream().collect(
    Collectors.toMap(Site::getId, Function.identity())
);

// 根據站點映射集查找詞條所屬站點
resList.forEach(res -> {
    Site site = siteMap.getOrDefault(res.getSiteId(), new Site().setName("-"));
    // System.out.println(
    //     String.format("%s, page from ==> %s", res.getName(), site.getName())
    // );
});
log.info("new method complete in ==> {}", Instant.now().toEpochMilli() - tn1);
// new method complete in ==> 86

結果顯示,老方法耗時627ms, 使用IN查詢+映射集只需要86ms

樹形結構建立

/*************************************************************************
* 【需求:將某篇資源的所有評論整理成樹形結構(root 10個元素,2層樹形)】
*************************************************************************/
/******************************** old  ********************************/
long to2 = Instant.now().toEpochMilli();
// 查詢一級評論
List<Comment> parentComments = commentService.selectByExample(
    Example.builder(Comment.class).andWhere(
        Sqls.custom().andEqualTo("sourceId", 1L).andIsNull("childOfId")
    ).orderByDesc("createdAt").build()
);

// 遍歷一級評論構造子評論列表
List<List<Comment>> resultOld = parentComments.stream().map(parentComment -> {
    List<Comment> childs = commentService.select(
        new Comment().setSourceId(parentComment.getSourceId()).setChildOfId(parentComment.getId())
    );
    // do something
    return childs;
}).collect(Collectors.toList());
log.info("old tree build in ==> {}", Instant.now().toEpochMilli() - to2);
// old tree build in ==> 1219

/******************************** new  ********************************/
long tn2 = Instant.now().toEpochMilli();
// 查詢所有評論
List<Comment> comments = commentService.selectByExample(
    Example.builder(Comment.class).andWhere(
        Sqls.custom().andEqualTo("sourceId", 1L)
    ).orderByDesc("createdAt").build()
);

// 根據評論父ID分組
Map<Long, List<Comment>> commentsMap = comments.stream().filter(
    e -> null != e.getChildOfId()
).collect(
    Collectors.groupingBy(Comment::getChildOfId, Collectors.toList())
);

// 篩選一級評論
List<Comment> rootComments = comments.stream().filter(
    e -> null == e.getChildOfId()
).collect(Collectors.toList());

// 遍歷一級評論,查找映射集中的子評論列表
List<List<Comment>> resultNew = rootComments.stream().map(e -> {
    List<Comment> childs = commentsMap.getOrDefault(e.getId(), Collections.emptyList());
    // do something
    return childs;
}).collect(Collectors.toList());
log.info("new tree build in ==> {}", Instant.now().toEpochMilli() - tn2);
// new tree build in ==> 98

結果顯示,老方法耗時1219ms, 使用新方法構造樹只需要98ms

結論

  儘量避免在stream中間函數做數據庫查詢,若情況合適,利用流式特性直接在內存進行篩選分組等操作,以此優化性能。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章