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

ネストされたListから特定のフィールドのListを作成する

Posted at

Stream#flatMapを使用する。

public class Foo {
    private List<Bar> bars;
    // getter/setter/constructor
}

public class Bar {
    private String piyo;
    // getter/setter/constructor
}

Fooリストから、ネストされたBarリストのフィールドpiyoのリストを作成する。

List<Foo> fooList 
    = Arrays.asList(new Foo(Arrays.asList(new Bar("piyo1"), new Bar("piyo2"))),
                    new Foo(Arrays.asList(new Bar("piyo3"), new Bar("piyo4"))));

List<String> piyoList 
    = fooList.stream().flatMap(foo -> foo.getBars().stream())
                      .map(Bar::getPiyo).collect(Collectors.toList());

System.out.println(piyoList); // piyo1, piyo2, piyo3, piyo4
1
1
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
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?