Wednesday, January 17, 2018

Java flatMap with example

In this post you will learn what is flatMap in Java8 and where we used flatMap. flatMap is a intermediate operation,which returns a new stream. Intermediate operations are classified as stateless and stateful operations based on need for sharing the information between elements while processing.

As per the Javadoc......

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.

The following example understand you how to use flatMap in java8.The same example if you write before java 8 then you could write multiple loops. But in Java 8 it could be like this

Example:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class FlatMapExample {
public static void main(String args[]) {
List<Zoo> zooList = new ArrayList<>();
Zoo nationalZoo = new Zoo("National");
nationalZoo.add("Lion");
 nationalZoo.add("Tiger");
 nationalZoo.add("Peacock");
      nationalZoo.add("Gorilla");

        Zoo aCountyZoo = new Zoo("Wills County");
        aCountyZoo.add("Peacock");
        aCountyZoo.add("Camelion");

        zooList.add(nationalZoo);
        zooList.add(aCountyZoo);

        // to get the aggregate
 List<String> animalList = zooList.stream()
                .flatMap(element -> element.getAnimals().stream())
                .collect(Collectors.toList());
System.out.println(animalList);

        // to get the unique set
Set<String> animalSet = zooList.stream()
                .flatMap(element -> element.getAnimals().stream())
                .collect(Collectors.toSet());
System.out.println(animalSet);
}
}
class Zoo {
private String zooName;
private Set<String> animals;
public Zoo(String zooName) {
this.zooName = zooName;
this.animals = new HashSet<>();
}
public void add(String animal) {
this.animals.add(animal);
}
public Set<String> getAnimals() {
return animals;
}
}

Output:
[Peacock, Lion, Tiger, Gorilla, Peacock, Camelion]
[Peacock, Lion, Tiger, Gorilla, Camelion]

Imagine that you want to create the following sequence: 1, 2, 2, 3, 3, 3, 4, 4, 4, 4 etc. (in other words: 1x1, 2x2, 3x3 etc.)

With flatMap it could look like:


IntStream sequence = IntStream.rangeClosed(1, 4)
                          .flatMap(i -> IntStream.iterate(i, identity()).limit(i));
sequence.forEach(System.out::println);

where:

IntStream.rangeClosed(1, 4) creates a stream of int from 1 to 4, inclusive
IntStream.iterate(i, identity()).limit(i) creates a stream of length i of int i - so applied to i = 4 it creates a stream: 4, 4, 4, 4
flatMap "flattens" the stream and "concatenates" it to the original stream

With Java < 8 you would need two nested loops:

List<Integer> list = new ArrayList<>();
for (int i = 1; i <= 4; i++) {
    for (int j = 0; j < i; j++) {
        list.add(i);
    }
}

No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...