54
49

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のmapとflatMapの違い

Posted at

Java 8のStreamにmap()flatMap()があります。その違いを検証します。

#結論
まず結論から言うと、
 ・map(T -> R)は、Tのデータ型をRのデータ型に1:1の変換です。
 ・flatMap(T -> Stream<R>)は、Tのデータ型からStream<R>に1:Nの変換です。

##Stream#map()

List<String> nameList = Arrays.asList("Tanaka", "Suzuki", "Takahashi");
Stream<Integer> stream = nameList.stream().map(x -> x.length());
System.out.println(stream.collect(Collectors.toList()));

上記の実行結果:

[6, 6, 9]
Tanaka Suzuki Takahashi
6 6 9
上記のように文字列(String)から文字列長(Integer)へ1:1の変換です。

##Stream#flatMap()

List<String> nameList = Arrays.asList("Tanaka", "Suzuki", "Takahashi");
Stream<Object> stream = nameList.stream().flatMap(x -> Stream.of(x, x.length()));
System.out.println((stream.collect(Collectors.toList())));

上記の実行結果:

[Tanaka, 6, Suzuki, 6, Takahashi, 9]
Tanaka Suzuki Takahashi
Tanaka, 6 Suzuki, 6 Takahashi, 9
文字列(String)から[文字列(String), 文字列長(Integer)]へ1:Nの変換です。
但し、その場合は2次元配列が生成されるわけではなく、flatなStreamが返却されます。
54
49
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
54
49

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?