Wednesday, 28 November 2018

what is flatMap in java 8

flatMap is an intermediate operation of the Java 8 Stream API.
which returns a new stream. Intermediate operations are classified as stateless and stateful operations based on need for sharing information between elements when processing them. flatMap is a stateless intermediate operation
As per the Javadoc,

“…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…”


Let do by example 

Following example will help you to understand this flatMap and a possible example scenario. Let us consider a zoo and the list of animals in it. Then we can use the flatMap to get an aggregate of animals in a list of Zoo. If we use the Pre-Java8 approach, we would be doing this by using multiple for-loops. Now the same can be achieve with Java 8 Stream API as below. 


flatMap 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;
 }
}

Example Output

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

No comments:

Post a Comment