では、これまで作った for文 vs Stream API の比較フロー と 実務でよく使う Stream API パターン集 を統合して、
「現場でよくある処理例をすべて1枚で見れる初心者向け教材」 にまとめます。
for文 vs Stream API + 実務パターン集(1枚教材)
[データ入力] List<Employee> employees = [...Employeeオブジェクト...]
──────────── for文 vs Stream API ────────────
◆ for文(命令的)
List<String> result = new ArrayList<>();
for (Employee e : employees) {
if (e.getAge() > 30) { // 条件フィルタ
result.add(e.getName().toUpperCase()); // 変換 + 結果格納
}
}
result → ["ALICE", "CHARLIE", "DAVE"]
◆ Stream API(宣言的)
List<String> filteredStream = employees.stream()
.filter(e -> e.getAge() > 30) // 条件フィルタ
.map(Employee::getName) // 変換
.map(String::toUpperCase)
.collect(Collectors.toList()); // 結果格納
filteredStream → ["ALICE", "CHARLIE", "DAVE"]
──────────── Stream API 実務パターン ────────────
1️⃣ 条件抽出 (filter)
employees.stream()
.filter(e -> e.getAge() > 30)
.toList()
2️⃣ 変換 (map)
employees.stream()
.map(Employee::getName)
.toList()
3️⃣ 並び替え (sorted)
employees.stream()
.sorted(Comparator.comparing(Employee::getAge))
.toList()
4️⃣ 集計 (mapToInt / sum / average)
employees.stream()
.mapToInt(Employee::getSalary)
.sum()
5️⃣ グループ化 (groupingBy)
employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment))
6️⃣ 件数カウント (count)
employees.stream()
.filter(e -> e.getAge() > 50)
.count()
7️⃣ 最初・任意の1件 (findFirst / findAny)
employees.stream()
.filter(e -> e.getAge() > 40)
.findFirst()
8️⃣ 重複排除 (distinct)
employees.stream()
.map(Employee::getDepartment)
.distinct()
.toList()
9️⃣ ネストフラット化 (flatMap)
skills.stream()
.flatMap(List::stream)
.distinct()
.toList()
──────────── フローの考え方 ────────────
データ入力 → 中間操作(filter/map/sorted/flatMap) → 末端操作(toList/count/forEach) → 結果
──────────── 実務での使い分けポイント ────────────
| filter | 条件抽出・未処理データ確認 |
| map | DTO変換・画面表示用データ |
| sorted | ソート済み一覧表示・レポート |
| mapToInt | 集計・分析レポート |
| groupingBy | 部署別集計・カテゴリ別集計 |
| count | 件数確認・閾値判定 |
| findFirst / findAny | 先頭データ取得・最初の有効値取得 |
| distinct | 重複排除・ユニーク一覧 |
| flatMap | ネスト構造のフラット化 |
──────────── 初心者向けコツ ────────────
1. 中間操作(filter/map/sorted/flatMap)は遅延実行
2. 末端操作(toList/count/forEach)で初めて処理が実行される
3. 副作用は末端で最小限にする
4. チェーンで順序を揃えると可読性アップ
✅ この1枚教材で、以下が一目で理解できます:
- for文で書く手順と Stream API で書く宣言的処理の違い
- 初心者でも安全に書ける Stream の基本フロー
- 実務でよく使う9つのパターン(filter / map / sorted / groupingBy / flatMapなど)
- 集計・変換・重複排除・グループ化・件数カウントなど現場コードで頻出の操作
- 遅延実行や副作用の注意点も明記


