# Java Streams ## Overview As part of Java 8 new features, lambda expressions are now supported (Project Lambda). See this very easy-to-read article from Brian Goetz [State of the Lambda](http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html) but more importantly focusing more on streams: [State of the Lambda: Libraries Edition](https://cr.openjdk.java.net/~briangoetz/lambda/lambda-libraries-final.html) ## Quick ways to create a stream ```java // From parameters Stream s = Stream.of("a", "b"); // From arrays Arrays.stream(myArray) // From collections myCollections.stream() // you also have specialized streams like IntStream, LongStream, DoubleStream, some example below: IntStream ints = IntStream.range(0, 10_000); IntStream rdInts = new Random().ints(1000); ``` ## Most common methods * ```filter()``` * ```mapToInt```, ```mapToObj``` * ```map()``` * ```collect()``` * ```findAny()```, ```findFirst()```, ```noneMatch()``` * ```forEach()``` * ```distinct()``` * ```sorted()``` ```sorted(Comparator)``` ## Differences map() and flatmap() These functions can be applied to * Optional * Stream ### map() ```map()``` returns a stream consisting of the results of applying the parameter function to the elements of the stream. This can potentially leads to producing output of type ```Stream>```, which are hard to work with. In such cases, ```flatmap()``` can be used (see below). ### flatMap() ```flatMap()```, as it names indicates, _flattens_ the result. Unlike ```map()``` which is only performing a transformation on each element of the stream, ```flatMap()``` also perform flattening of the inner streams in the stream resulting from the transformation. Example: ```java String[] arr = { "map", "flatmap" }; Arrays.stream(arr).flatMap(word -> word.chars().mapToObj(o -> (char) o)).forEach(System.out::println); ``` This prints: ``` m a p f l a m a p ``` ## From stream to collection Example, use: ```mystream.collect(Collectors.toList())```, ```mystream.collect(Collectors.toCollection(ArrayList::new)``` ## From stream to array Example, use: ```mystream.toArray(String[]::new)``` ## Reduction operations * ```reduce(identity, BinaryOperator accumulator)``` Example: ```java String[] myArray = { "Where", "is", "my", "stream", "?" }; String result = Arrays.stream(myArray) .reduce("", (a,b) -> a + " " + b); assert result.equals(" Where is my stream ?"); ``` Others... * ```sum()``` * ```average()``` * ```count()``` ## Parallelization The motivation behind the stream API was mostly to enable easy parallelization Use these methods: * ``myStream.parallel()`` * ``myCollection.parallelStream()``