【JAVA8】stream 流相關操作

1. 查找流中滿足條件的第一個元素

【集合】.stream()
        .filter(item -> 【條件】)
        .findAny()
        .get();

【集合】.stream()
        .filter(item -> 【條件】)
        .findFirst()
        .get();

2. 內循環

【集合】.stream()
        .forEach(item -> {
           【代碼】
        });

3. 將集合轉換爲MAP

// Function.identity() 當前實體
【集合】.stream()
        .collect(Collectors.toMap(item -> 【鍵值】), Function.identity()));
4. 集合類型轉換
【集合】.stream()
        .map(item -> 【代碼】)
        .collect(Collectors.toList());
5. 求和
long result = 【集合】.stream()
                      .map(item -> {
                        【代碼】
                      })
                      .reduce(0, Integer::sum);

6. 分組

【集合】.stream()
        .map(item -> 【代碼】)
        .collect(Collectors.groupingBy(Record::getUserId));

【集合】.stream() 
        .map(item -> 【代碼】) 
        .collect(Collectors.groupingBy(Record::getUserId, 
                                       Collectors.reducing(BigDecimal.ZERO, Record::getOutput, BigDecimal::add)));

7. 排序(取前N個對象)

【集合】.stream()
        .map(item -> 【代碼】)
        .sorted(Comparator.comparing(Expression::getPriority))
        .collect(Collectors.toList());

【集合】.stream()
        .map(item -> 【代碼】)
        .sorted((x, y) -> y.getOutput().compareTo(x.getOutput()))
        .limit(10)
        .collect(Collectors.toList());

8. 判斷所有爲真或假

【集合】.stream()
        .map(item -> update(item))
        .allMatch(result -> 1 == result);

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