Transforming Data with Java 8 Streams API: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 13: Line 13:
The Stream API exposes the <tt>map()</tt> method, which converts the stream's elements into elements of another type, offered also as a stream. The conversion if performed by a [[Java.util.function.Function#Overview|Function<T, R>]] presented as the argument of the <tt>map()</tt> method.  
The Stream API exposes the <tt>map()</tt> method, which converts the stream's elements into elements of another type, offered also as a stream. The conversion if performed by a [[Java.util.function.Function#Overview|Function<T, R>]] presented as the argument of the <tt>map()</tt> method.  


<syntaxhighlight lang='java'>
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
</syntaxhighlight>


=Flat-Mapping Data=


=====<tt>map()</tt>=====


<tt>map()</tt> takes a lambda that transforms an element of a certain type into an element of a different type, by applying a [[Java.util.function.Function#Overview|function]], and pushing it to the the result stream.
<syntaxhighlight lang='java'>
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
</syntaxhighlight>


=====<tt>flatMap()</tt>=====
=====<tt>flatMap()</tt>=====

Revision as of 18:11, 28 March 2018

Internal

Overview

The Stream API offers the possibility to intercept a stream and converts its elements into elements of another type, offered also as a stream. This operations is conventionally named mapping. The world mapping is used because it has a meaning similar to transforming, but with the nuance of "creating a new version" rather than "modifying".

Mapping Data

https://docs.oracle.com/javase/10/docs/api/java/util/stream/Stream.html#flat(java.util.function.Function)

The Stream API exposes the map() method, which converts the stream's elements into elements of another type, offered also as a stream. The conversion if performed by a Function<T, R> presented as the argument of the map() method.

<R> Stream<R> map(Function<? super T, ? extends R> mapper);

Flat-Mapping Data

flatMap()

flatMap() returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have been placed into this stream. If a mapped stream is null an empty stream is used, instead.

https://docs.oracle.com/javase/10/docs/api/java/util/stream/Stream.html#flatMap(java.util.function.Function)
<R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)

Example:

List<String> uniqueChars = words.
    stream().
    map(word -> word.split("")).
    flatMap(Arrays::stream).
    distinct().
    collect(toList());