1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Java】ChatGPTに作ってもらったStreamAPI問題をといてみた(前半編)

1
Last updated at Posted at 2026-01-20

はじめに

Javaの Stream API はとても便利ですが、
IT初心者にとっては

  • 何をしているのか分かりにくい
  • for文のほうが安心する
  • map / filter / collect が混乱する

という壁があります。

そこで今回は、ChatGPTにStream APIの練習問題を作ってもらい
実際に解きながら「何をしているのか」を初心者向けに解説します。
10問作成してもらったので前半編と後半編に分けて紹介します。


使用するクラス

class Employee {
    private String name;
    private String department;
    private int age;
    private int salary;

    public Employee(String name, String department, int age, int salary) {
        this.name = name;
        this.department = department;
        this.age = age;
        this.salary = salary;
    }

    public String getName() { return name; }
    public String getDepartment() { return department; }
    public int getAge() { return age; }
    public int getSalary() { return salary; }
}
public class Main {
    List<Employee> employees = List.of(
        new Employee("佐藤", "営業", 28, 400000),
        new Employee("鈴木", "営業", 35, 550000),
        new Employee("高橋", "開発", 30, 600000),
        new Employee("田中", "開発", 45, 800000),
        new Employee("伊藤", "人事", 32, 450000)
    );
}

問題1:開発部の社員名を取得する

回答コード

employees.stream()
    .filter(e -> "開発".equals(e.getDepartment()))
    .map(Employee::getName)
    .toList();

出力結果

[高橋, 田中]

解説

  • filter:条件に合うものだけ残す
  • map:中身を別の形に変換する
  • Employee → String(名前) に変換している

問題2:全社員の給与合計を求める

回答コード

employees.stream()
    .mapToInt(Employee::getSalary)
    .sum();

出力結果

2800000

解説

  • mapToInt:数値専用のStreamに変換
  • sum():合計を出す

問題3:社員の平均年齢を求める

回答コード

employees.stream()
    .mapToInt(Employee::getAge)
    .average();

出力結果

OptionalDouble[34.0]

解説

  • average()OptionalDouble を返す
  • データが存在しない場合を考慮している

問題4:最も低い給与を求める

回答コード

employees.stream()
    .mapToInt(Employee::getSalary)
    .min();

出力結果

OptionalInt[400000]

問題5:30歳以上の社員数を求める

回答コード

employees.stream()
    .filter(e -> e.getAge() >= 30)
    .count();

出力結果

4

前半まとめ

  • filter:条件指定
  • map / mapToInt:変換
  • sum / average / count:集計

Stream APIは 「処理の流れを読むAPI」 だと理解すると楽になります。

※後半編はこちらです。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?