chiperortiz chiperortiz - 1 year ago 145
Java Question

Java 8 Streams FlatMap method example

I have been checking the upcoming

Java update
, namely:
Java 8 or JDK 8
. Yes, I am impatient, there's a lot of new stuff, but, there is something I don't understand, some simple code:

final Stream<Integer>stream = Stream.of(1,2,3,4,5,6,7,8,9,10);

the javadocs are

public <R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)

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.)
This is an intermediate operation.

I would appreciate if somebody created some simple real-life examples about
, how you could code it in previous java versions
and how you can code the same routines using
Java 8

Answer Source

It doesn't make sense to flatMap a Stream that's already flat, like the Stream<Integer> you've shown in your question.

However, if you had a Stream<List<Integer>> then it would make sense and you could do this:

Stream<List<Integer>> integerListStream = Stream.of(
  Arrays.asList(1, 2), 
  Arrays.asList(3, 4), 

Stream<Integer> integerStream = integerListStream .flatMap(Collection::stream);

Which would print:


To do this pre-Java 8 you just need a loops:

List<List<Integer>> integerLists = Arrays.asList(
  Arrays.asList(1, 2), 
  Arrays.asList(3, 4), 

List<Integer> flattened = new ArrayList<>();

for (List<Integer> integerList : integerLists)

for (Integer i : flattened)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download