では、実務でよく使う Stream API のパターン(filter / map / sorted / groupingBy / collect など)をまとめた1枚図 を作ります。
初心者でも現場コードにそのまま使えるイメージで整理しました。
実務でよく使う Stream API パターン(初心者向け1枚図)
[データ入力] List<Employee> employees = [...Employeeオブジェクト...]
──────────── Stream API パターン ────────────
1️⃣ 条件で抽出 (filter)
employees.stream()
.filter(e -> e.getAge() > 30)
.toList()
→ 年齢30以上の社員だけ抽出
2️⃣ 変換 (map)
employees.stream()
.map(Employee::getName)
.toList()
→ 社員名だけのリストに変換
3️⃣ 並び替え (sorted)
employees.stream()
.sorted(Comparator.comparing(Employee::getAge))
.toList()
→ 年齢順に並び替え
4️⃣ 集計 (mapToInt / sum / average / max / min)
employees.stream()
.mapToInt(Employee::getSalary)
.sum()
→ 給与の合計を算出
5️⃣ グループ化 (groupingBy)
employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment))
→ 部署ごとに社員をグループ化
6️⃣ 件数カウント (count)
long seniorCount = employees.stream()
.filter(e -> e.getAge() > 50)
.count()
→ 50歳以上の社員数を取得
7️⃣ 最初・任意の1件 (findFirst / findAny)
Optional<Employee> firstEmployee = employees.stream()
.filter(e -> e.getAge() > 40)
.findFirst()
→ 条件に合う最初の社員を取得
8️⃣ 重複排除 (distinct)
employees.stream()
.map(Employee::getDepartment)
.distinct()
.toList()
→ 部署名の重複を除いたリスト
9️⃣ ネストフラット化 (flatMap)
List<List<String>> skills = ...
skills.stream()
.flatMap(List::stream)
.distinct()
.toList()
→ 二重リストを1つにまとめて重複削除
─────────────────────────────────────
💡 フローの考え方
データ入力 → 中間操作(filter/map/sorted/flatMap) → 末端操作(toList/count/forEach) → 結果
実務での使い分けポイント
| パターン | 実務用途 |
|---|---|
| filter | 条件抽出、未処理データ確認 |
| map | DTO変換、画面表示用データ作成 |
| sorted | ソート済み一覧表示、レポート生成 |
| mapToInt / sum / average | 集計・分析レポート |
| groupingBy | 部署別集計、カテゴリ別集計 |
| count | 件数確認、閾値判定 |
| findFirst / findAny | 先頭データ取得、最初の有効値取得 |
| distinct | 重複排除、ユニーク一覧 |
| flatMap | ネスト構造のフラット化、複数リスト統合 |
💡 初心者向けコツ
- 中間操作(filter/map/sorted/flatMap)は遅延実行
- 末端操作(toList/count/forEach)で処理が実行される
- 副作用は末端で最小限にする
- チェーンで順序を揃えると可読性が高くなる


