mapping in Java 8 streams

  • Last Updated: February 24, 2024
  • By: javahandson
  • Series
img

mapping in Java 8 streams

In this article, we will try to understand what is mapping in Java 8 streams with examples. If you want to learn more about other Java, Java 8, or Spring concepts then please click the above menu options.

The word mapping means transforming from one form to another. Here we will not modify the existing stream instead we will be creating a new stream by applying some transformation logic.

There are 4 mapping methods defined in the Stream interface for performing the mapping operation. We will understand them one by one in the below sections.

map method

The Stream interface has a map method that takes a function as an argument. This function is applied to all the elements of the existing stream and a new transformed stream is created out of it.

If you want to know more about Function interface then please check this article on predefined functional interfaces

Note* map is an intermediate function which means it will not get executed until some terminal operation is executed. Ex. forEach is a terminal operation.

Syntax of the map method

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

Type Parameters: 
R - The element type of the new stream

Arguments: 
mapper - It is a stateless function that will be applied to each element.

Returns: A new transformed stream

Write a program to double the value of numbers in a stream ( multiply each element in a stream with 2 )

package com.javahandson.map;

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

public class MapElements {
    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);

        List<Integer> transformedStream = list.stream()
                .map(number -> number * 2)
                .collect(Collectors.toList());

        System.out.println("Transformed stream : "+transformedStream);
    }
}
Output: Transformed stream : [2, 4, 6, 8, 10, 12]

In the above program, we have taken a list of numbers and applied a mapping function on that stream to double the value of the given numbers.

Write a program to get the names of students from a list of Student objects.

package com.javahandson.map;

public class Student {

    int rollNumber;
    String name;
    char grade;

    Student(int rollNumber, String name, char grade) {
        this.rollNumber = rollNumber;
        this.name = name;
        this.grade = grade;
    }

    public int getRollNumber() {
        return rollNumber;
    }

    public String getName() {
        return name;
    }

    public char getGrade() {
        return grade;
    }
}
package com.javahandson.map;

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

public class MapElements {
    public static void main(String[] args) {

        Student s1 = new Student(101, "Suraj", 'C');
        Student s2 = new Student(102, "Iqbal", 'A');
        Student s3 = new Student(103, "Amar", 'B');
        Student s4 = new Student(104, "Amit", 'C');
        Student s5 = new Student(105, "Suchit", 'A');

        List<Student> students = Arrays.asList(s1, s2, s3, s4, s5);

        List<String> names = students.stream()
                .map(Student::getName)
                .collect(Collectors.toList());

        System.out.println("Name of students : "+ names);
    }
}
Output: Name of students : [Suraj, Iqbal, Amar, Amit, Suchit]

In the above program, we have taken a list of students and applied a mapping function on that stream to fetch their names.

mapToInt method

The Stream interface has a mapToInt method that takes a ToIntFunction as an argument. This function is applied to all the elements of the existing stream and a new transformed IntStream is created out of it.

ToIntFunction is a functional interface that produces an integer value results.

IntStream is a sequence of primitive integer value elements that supports sequential and parallel aggregate operations.

Syntax of the mapToInt method

IntStream mapToInt(ToIntFunction<? super T> mapper)

Parameters:
mapper - It is a stateless function that will be applied to each element.

Returns: A new transformed stream that contains the integer elements

Write a program to get the roll numbers of students from the list of Student objects using mapToInt method.

package com.javahandson.map;

import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;

public class MapToIntElements {
    public static void main(String[] args) {

        Student s1 = new Student(101, "Suraj", 'C');
        Student s2 = new Student(102, "Iqbal", 'A');
        Student s3 = new Student(103, "Amar", 'B');
        Student s4 = new Student(104, "Amit", 'C');
        Student s5 = new Student(105, "Suchit", 'A');

        List<Student> students = Arrays.asList(s1, s2, s3, s4, s5);

        IntStream intStream = students.stream().mapToInt(Student::getRollNumber);
        int[] rollNumbers = intStream.toArray();

        System.out.print("Roll Numbers are : ");
        for(int rollNumber : rollNumbers) {
            System.out.print(rollNumber + " ");
        }
    }
}
Output: Roll Numbers are : 101 102 103 104 105 

mapToLong method

The Stream interface has a mapToLong method that takes a ToLongFunction as an argument. This function is applied to all the elements of the existing stream and a new transformed LongStream is created out of it.

ToLongFunction is a functional interface that produces long-value results.

LongStream is a sequence of primitive long-value elements that supports sequential and parallel aggregate operations.

Syntax of the mapToLong method

LongStream mapToLong(ToLongFunction<? super T> mapper)

Parameters:
mapper - It is a stateless function that will be applied to each element.

Returns: A new transformed stream that contains the long type elements

Write a program to convert a list of elements from integer type to long type using mapToLong method.

 package com.javahandson.map;

import java.util.Arrays;
import java.util.List;

public class MapToLongElements {
    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);

        long[] numbers =  list.stream()
                .mapToLong(number -> Long.valueOf(number))
                .toArray();

        System.out.print("Numbers are : ");
        for(long number : numbers) {
            System.out.print(number + " ");
        }
    }
}
Output: Numbers are : 1 2 3 4 5 6

mapToDouble method

The Stream interface has a mapToDouble method that takes a ToDoubleFunction as an argument. This function is applied to all the elements of the existing stream and a new transformed DoubleStream is created out of it.

ToDoubleFunction is a functional interface that produces double-value results.

DoubleStream is a sequence of primitive double-value elements that supports sequential and parallel aggregate operations.

Syntax of the mapToDouble method

DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper)

Parameters:
mapper - It is a stateless function that will be applied to each element.

Returns: A new transformed stream that contains the double type elements

Write a program to convert a list of elements from integer type to double type using mapToDouble method.

package com.javahandson.map;

import java.util.Arrays;
import java.util.List;

public class MapToDoubleElements {
    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);

        double[] numbers = list.stream()
                .mapToDouble(number -> Double.valueOf(number))
                .toArray();

        System.out.print("Numbers are : ");
        for(double number : numbers) {
            System.out.print(number + " ");
        }
    }
}
Output: Numbers are : 1.0 2.0 3.0 4.0 5.0 6.0

Solidify understanding of map

Given a list of words return the list of the number of characters for each word.

Here we will take a mapper function that calculates the length of a word. The length of a word denotes the number of characters in that word.

package com.javahandson.map;

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

public class WordLength {
    public static void main(String[] args) {

        List<String> languages = Arrays.asList("Java", "C++", "Python", ".Net", "Javascript");

        List<Integer> wordsLength = languages.stream()
                .map(language -> language.length())
                .collect(Collectors.toList());

        for (int i=0; i<languages.size() ; i++) {
            System.out.println(languages.get(i) + " word length is : "+ wordsLength.get(i));
        }
    }
}

Output:
Java word length is : 4
C++ word length is : 3
Python word length is : 6
.Net word length is : 4
Javascript word length is : 10

So this is all about mapping in Java 8 streams with examples. If you have any questions on this topic please raise them in the comments section.

If you liked this article then please share this post with your friends and colleagues so that they can learn about Java and its frameworks in more depth.

Leave a Comment