0
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】3分で読めるStreamAPIの基本知識

Posted at

StreamAPIとは

リストなどのコレクションを処理するAPIのこと

特徴

  • 繰り返し処理やフィルタ処理を簡単にかける
  • 中間処理(map,filterなど)終端処理(collect,forEachなど) で構成

StreamAPIの使用例

▼例題
List<String>に格納された名前のうち、
"a"で始まる小文字の名前を大文字に変換し、結果をリストに格納する

▼StreamAPIを使わない場合

List<String> names = Arrays.asList("alice","bob","anna","Charie");
List<String> result = new ArrayList<>();

for(String name: names) {
    if(name.startsWith("a")) {
        result.add(name.toUpperCase());
    }
}

System.out.println(result); // [ALICE,ANNA]

▼StreamAPIを使用した場合

List<String> names = ("alice","bob","anna","Charlie");

List<String> result = names.stream()
    .filter(name -> name.startWith("a")) // 条件に合うものを選ぶ
    .map(String::toUpperCase) // 大文字に変換
    .collect(Collectors.toList()); // Listにまとめる

System.out.println(result); // [ALICE,ANNA]

まとめ

  • StreamAPIの場合、処理の目的が、filter,map,collectなど直感的で読みやすい。
  • データの変換処理をパイプラインのように繋げて記述できる。

記事作成時間:20分

0
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
0
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?