LoginSignup
0
2

More than 3 years have passed since last update.

Java の Stream で List を List<String> に変換するサンプルコード

Posted at
// List に入れる要素のクラス
public class MyData {

  public final String name;
  public final Integer age;

  public MyData(String name, Integer age) {
    this.name = name;
    this.age = age;
  }

  public String getMyInfo() {
    return name + "(" + age + ")";
  }
}
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class Main {

  public static void main(String[] args) {

    // データを構築
    List<MyData> list = new ArrayList<>() {
      {
        add(new MyData("Alice", 88));
        add(new MyData("Bob", 8));
        add(new MyData("Carol", null));
        add(null);
      }
    };

    // 変換例1
    List<String> list1 = list.stream() // Stream オブジェクトを生成
      .filter(Objects::nonNull)        // 要素が null のものを排除
      .map(MyData::getMyInfo)          // 要素ごとに文字列を生成
      .collect(Collectors.toList());   // List 化
    System.out.println(String.join("\n", list1));

    // 変換例2
    List<String> list2 = list.stream()                // Stream オブジェクトを生成
      .filter(Objects::nonNull)                       // 要素が null のものを排除
      .map(mydata -> mydata.name + ": " + mydata.age) // 要素ごとに文字列を生成
      .collect(Collectors.toList());                  // List 化
    System.out.println(String.join("\n", list2));

    // 変換例3
    List<String> list3 = list.stream() // Stream オブジェクトを生成
      .filter(Objects::nonNull)        // 要素が null のものを排除
      .map(mydata -> {                 // 要素ごとに文字列を生成
        if (mydata.age == null) {
          return mydata.name;
        } else {
          return mydata.name + ": " + mydata.age;
        }
      })
      .collect(Collectors.toList());   // List 化
    System.out.println(String.join("\n", list3));
  }
}

Java 15 (AdoptOpenJDK 15+36) による実行結果。

$ javac *.java
$ java Main
Alice(88)
Bob(8)
Carol(null)
Alice: 88
Bob: 8
Carol: null
Alice: 88
Bob: 8
Carol

参考: Stream (Java Platform SE 8 )

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