2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Stream#collectを使用してJavaBeanリストから特定のフィールドのみを取得してリスト化する

Posted at

以下のHogeクラスをサンプルとして使う。

public class Hoge {

    private String foo;

    private String bar;

    public Hoge(String foo, String bar) {
        this.foo = foo;
        this.bar = bar;
    }

    // getter/setter
}

Stream#collectを使用してHoge#barのリストを作成する。

// Hogeリストを作成
List<Hoge> hoges = Arrays.asList(new Hoge("f001", "b001")
                               , new Hoge("f002", "b002")
                               , new Hoge("f003", "b003"));
// Hoge#barのリストを作成
List<String> bars = hoges.stream().collect(ArrayList::new
                                        , (l, h) -> l.add(h.getBar())
                                        , (l1, l2) -> l1.addAll(l2));

System.out.println(bars); // [b001, b002, b003]
2
1
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?