Last active
April 29, 2021 13:21
-
-
Save mtorchiano/00cf48bd9f55161e14147039b1030048 to your computer and use it in GitHub Desktop.
Source code for the video example of Stream.flatMap() available at: <https://youtu.be/ouinDyk-H0c>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.stream.Stream; | |
import it.polito.po.data.Lyrics; | |
/** | |
* Explaining how Stream.flatMap() works | |
* with a simple code example... | |
* @author mtk | |
* | |
*/ | |
public class FlatMapExplained { | |
public static void main(String[] args) { | |
String text = Lyrics.ALL_ALONG_THE_WATCHTOWER; | |
// let us split this song lyric into words... | |
// First of all we have to create a stream | |
// out of the String text variable | |
Stream<String> st = Stream.of(text); | |
// then we need to split the text into words | |
// using the split function of String | |
Stream<String[]> swa = st.map( l -> l.split("[ ,.!?]+")); | |
// though the resulting stream has String[] as elements... | |
//..while we would like to have String (its elements) | |
// we need to flat out the aggregate type into | |
// its individual elements. | |
// this is exactly what flat map is doing | |
Stream<String> sw = swa.flatMap( a -> Arrays.stream(a) ); | |
// Now that finally we have our stream of words | |
// we can print it out (e.g.) | |
sw.forEach(System.out::println); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment