weblog

技術的なメモ置き場。

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

public class Hoge {
    private String foo;
    private String bar;
    // constructor/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]

mapの場合

hoges.stream().map(Hoge::getBar).collect(Collectors.toList());