Home » Core Java » Java 8 Stream – Map & Collect Example

About Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).

Java 8 Stream – Map & Collect Example

Hello. In this tutorial, we will explain the most commonly used Java 8 Stream APIs: the map() and collect() methods.

1. Introduction

Before diving deep into the practice stuff let us understand the map and collect methods.

1.1 map() method

This method is used to convert an object to something else. Represented by the syntax –

map() method

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

1.2 collect() method

This method is used to collect the result of the stream pipeline in a collection (such as List, Set, or Map).

collect() method

<R, A> R collect(Collector<? super T, A, R> collector)

2. Practice

Let us dive into some practice stuff from here and I am assuming that you already have the Java 1.8 or greater installed in your local machine. I am using JetBrains IntelliJ IDEA as my preferred IDE. You’re free to choose the IDE of your choice.

2.1 Model class

Create a java file in the com.jcg.assignment.util package and add the following content to it.

Student.java

package com.jcg.assignment.util;

import java.util.ArrayList;
import java.util.List;

public final class Student {
    private final int id;
    private final String name;
    private final double cgpa;

    private Student(final int id, final String name, final double cgpa) {
        this.id = id;
        this.name = name;
        this.cgpa = cgpa;
    }

    //util method
    public static List<Student> createStudents() {
        final List<Student> students = new ArrayList<>();
        //adding students
        students.add(new Student(101, "John P.", 7.51));
        students.add(new Student(102, "Sarah M.", 9.67));
        students.add(new Student(103, "Charles B.", 4.5));
        students.add(new Student(104, "Mary T.", 8.7));

        return students;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public double getCgpa() {
        return cgpa;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", cgpa=" + cgpa +
                '}';
    }
}

2.2 DTO class

Create a java file in the com.jcg.assignment.util package and add the following content to it. This class will be used to map the model attributes with the dto attributes.

StudentDto.java

package com.jcg.assignment.util;

public final class StudentDto {

    private final int studentId;
    private final String studentName;
    private final double studentPercentage;

    public StudentDto(final int studentId, final String studentName, final double studentCgpa) {
        this.studentId = studentId;
        this.studentName = studentName;
        this.studentPercentage = studentCgpa * 10;
    }

    public int getStudentId() {
        return studentId;
    }

    public String getStudentName() {
        return studentName;
    }

    public double getStudentPercentage() {
        return studentPercentage;
    }

    @Override
    public String toString() {
        return "StudentDto{" +
                "studentId=" + studentId +
                ", studentName='" + studentName + '\'' +
                ", studentPercentage=" + studentPercentage +
                '}';
    }
}

2.3 map() and collect() implementation

Create a java file in the com.jcg.assignment package and add the following content to it. The file will consist of two methods consisting of the dummy collection which is iterated upon and mapped accordingly.

Java8MapExample.java

package com.jcg.assignment;

import com.jcg.assignment.util.Student;
import com.jcg.assignment.util.StudentDto;

import java.util.List;
import java.util.stream.Collectors;

// map(...) method syntax
// <R> Stream<R>    map(Function<? super T,? extends R>mapper)

public class Java8MapExample {

    private static void prepareStringList() {
        // Using map function to convert Stream<Student> to Stream<String>
        final List<String> studentNames = Student.createStudents()
                .stream()
                .map(Student::getName)
                .collect(Collectors.toList());

        studentNames.forEach(System.out::println);
    }

    private static void convertToStudentDtoList() {
        // Using map function to convert Stream<Student> to Stream<StudentDto>
        final List<StudentDto> studentDtos = Student.createStudents()
                .stream()
                .map(student -> new StudentDto(student.getId(), student.getName(), student.getCgpa()))
                .collect(Collectors.toList());

        studentDtos.forEach(studentDto -> System.out.println(studentDto.toString()));
    }

    public static void main(String[] args) {
        prepareStringList();
        System.out.println("----------");
        convertToStudentDtoList();
    }
}

Run the file and if everything goes well the following output will be logged in the IDE console.

Console output

John P.
Sarah M.
Charles B.
Mary T.
----------
StudentDto{studentId=101, studentName='John P.', studentPercentage=75.1}
StudentDto{studentId=102, studentName='Sarah M.', studentPercentage=96.7}
StudentDto{studentId=103, studentName='Charles B.', studentPercentage=45.0}
StudentDto{studentId=104, studentName='Mary T.', studentPercentage=87.0}

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

3. Summary

In this tutorial, we learned the implementation of map and collect methods introduced in Java8 Stream API. You can download the source code from the Downloads section.

4. Download the Eclipse Project

This was a tutorial of learning and implementing the map and collect methods introduced in Java8 Stream API.

Download
You can download the full source code of this example here: Java 8 Stream – Map & Collect Example

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments