Java 8 Stream flatMap method Example

7 years ago Lalit Bhagtani 5

In this tutorial, we will learn about Java 8 stream flatMap method.

Java 8 Stream flatMap

flatMap() method :-

This method takes one Function as an argument, this function accepts one parameter T as an input argument and return one stream of parameter R as a return value. When this function is applied on each element of this stream, it produces a stream of new values. All the elements of these new streams generated by each element are then copied to a new stream, which will be a return value of this method. 

Syntax :-  <R> Stream<R> flatMap ( Function<? super T, ? extends Stream<? extends R>> mapper )

Reference :-  flatMap() method JavaDocs

Java 8 Stream flatMap

Problem Statement :-

Given a list of Student objects, find out names of all the courses opted by all the students.

Student POJO :- 

  public class Student {

    private String name;
    private String grade;
    private List<String> course; 
 
    public Student(String name, String grade, List<String> course) {
      super();
      this.name = name;
      this.grade = grade;
      this.course = course;
    }
    public String getName() {
      return name;
    }
    public void setName(String name) {
      this.name = name;
    }
    public String getGrade() {
      return grade;
    }
    public void setGrade(String grade) {
      this.grade = grade;
    }
    public List<String> getCourse() {
      return course;
    }
    public void setCourse(List<String> course) {
      this.course = course;
    }
  }

Java 7 :- To implement this, first iterate through the list of student objects. Then for each student object, get the list of its courses. Iterate through the list of courses and add each course name to the newly created Set object (set is used to remove duplicates).

  public static void main(String[] args){
 
    List<Student> studentList = new ArrayList<Student>();
 
    studentList.add(new Student("Robert","5st grade", Arrays.asList(new String[]{"history","math","geography"})));
    studentList.add(new Student("Martin","8st grade", Arrays.asList(new String[]{"economics","biology"})));
    studentList.add(new Student("Robert","9st grade", Arrays.asList(new String[]{"science","math"})));
 
    Set<Student> coursesSet = new HashSet<Student>();
 
    for(Student student:studentList){
      List<Student> courses = student.getCourse();
      for(String course:courses){
        coursesSet.add(course);
      }
    }
 
    System.out.println(coursesSet);
 
 }

Java 8 Stream flatMap :- Implementation using stream API.

  public static void main(String[] args){
 
    List<Student> studentList = new ArrayList<Student>();
 
    studentList.add(new Student("Robert","5st grade", Arrays.asList(new String[]{"history","math","geography"})));
    studentList.add(new Student("Martin","8st grade", Arrays.asList(new String[]{"economics","biology"})));
    studentList.add(new Student("Robert","9st grade", Arrays.asList(new String[]{"science","math"})));
 
    Set<Student> courses = studentList.stream().flatMap( e -> e.getCourse().stream()).collect(Collectors.toSet());
 
    System.out.println(courses);
 
  }

Result :- 

[economics, biology, geography, science, history, math]

Java 8 Stream API provide us three variation of Java 8 Stream flatMap method, which can be used in case of int, long and double. They are as follows:-

  1. IntStream flatMapToInt ( Function<? super T, ? extends IntStream> mapper ) 
  2. LongStream flatMapToLong ( Function<? super T, ? extends LongStream> mapper )
  3. DoubleStream flatMapToDouble ( Function<? super T, ? extends DoubleStream> mapper ) 

That’s all for Java 8 Stream flatMap method. If you liked it, please share your thoughts in comments section and share it with others too.