1
3

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.

for文のネストをstreamで書いてみる

Posted at

概要

for文をネストすることで、2つのリスト内要素の組み合わせを得られる。
Streamで同じことを行うとしたらどう書けば良いか。

for文

public static void main(String[] args) {

        List<Integer> numList = List.of(1, 2);
        List<String> strList = List.of("A", "B", "C");

        for (Integer i : numList) {
            for( String j : strList) {
                System.out.println(i + "," + j);
            }
        }
    }

出力

1,A
1,B
1,C
2,A
2,B
2,C

Stream

flatMapを用いて1,N変換を行い、変換を行った要素をmapで整えてあげれば良い。

public static void main(String[] args) {

        List<Integer> numList = List.of(1, 2);
        List<String> strList = List.of("A", "B", "C");

        numList.stream().flatMap(i -> strList.stream().map(j -> i +","+ j))
                .forEach(System.out::println);
    }

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?