Ebooks

Java Stream map

Java Stream map tutorial shows how to perform map operations on Java streams.

Java Stream

Java Stream is a sequence of elements from a source that supports aggregate operations. Streams do not store elements; the elements are computed on demand. Elements are consumed from data sources such as collections, arrays, or I/O resources.

Stream aggregate operations are similar to SQL operations. We can apply filtering, mapping, reducing, matching, searching, or sorting operations on streams. Streams allow chaining of multiple stream operations. Unlike collections which use external iterations, streams are iterated internally.

Java Stream map

We can change stream elements into a new stream; the original source is not modified. The map() method returns a stream consisting of the results of applying the given function to the elements of a stream. The map() is an itermediate operation.

Java Stream map example

In the first example, we map an arithmetic operation on a list of values.

JavaStreamMapEx.java
package com.zetcode;

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

public class JavaStreamMapEx {

    public static void main(String[] args) {

        var nums = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8);

        var squares = nums.map(e -> e * e).toArray();

        System.out.println(Arrays.toString(squares));
    }
}

In the example, we create a stream of integers. With the map() method we apply an arithmetic operation on the values and then transform them into an array.

[1, 4, 9, 16, 25, 36, 49, 64]

This is the output.

Java Stream map example II

In the following example, we use map() and mapToInt() methods in one stream.

JavaStreamMapEx2.java
package com.zetcode;

import java.util.Random;
import java.util.stream.Stream;

public class JavaStreamMapEx2 {

    public static void main(String[] args) {

        Stream.generate(new Random()::nextDouble)
                .map(e -> (e * 100))
                .mapToInt(Double::intValue)
                .limit(5)
                .forEach(System.out::println);
    }
}

The example generates five random double values. Using the mapping methods, each of the randomly generated values is multiplied by 100 and transformed into integer.

66
25
18
35
47

This is a sample output.

Java Stream map example III

In the next example, we map a custom method on a stream of strings.

JavaStreamMapEx3.java
package com.zetcode;

import java.util.stream.Stream;

public class JavaStreamMapEx3 {

    public static void main(String[] args) {

        var words = Stream.of("cardinal", "pen", "coin", "globe");
        words.map(JavaStreamMapEx3::capitalize).forEach(System.out::println);
    }

    private static String capitalize(String word) {

        word = word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase();
        return word;
    }
}

The example capitalizes each of the words in the stream.

Cardinal
Pen
Coin
Globe

This is the output.

Java Stream map example IV

In the next example, we read values from a CSV file into a list using map methods.

src/resources/numbers.csv
2,3,5,6,1,0
9,5,6,3,2,1

We have these values in the numbers.csv file.

JavaStreamMapEx4.java
package com.zetcode;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collectors;

public class JavaStreamMapEx4 {

    public static void main(String[] args) throws IOException {

        var lines = Files.readAllLines(Path.of("src/resources/numbers.csv"));

        var vals = lines.stream().map(line-> Arrays.asList(line.split(",")))
                .flatMap(Collection::stream).mapToInt(Integer::valueOf)
                .boxed().collect(Collectors.toList());

        System.out.println(vals);
    }
}

First, we read the CSV file into a list of strings. Then we create a stream from the list and apply mapping methods to get a list of integers in the end.

var lines = Files.readAllLines(Path.of("src/resources/numbers.csv"));

With Files.readAllLines(), we read all lines of the file into a list of strings.

var vals = lines.stream().map(line-> Arrays.asList(line.split(",")))
        .flatMap(Collection::stream).mapToInt(Integer::valueOf)
        .boxed().collect(Collectors.toList());

We create a stream from the list, split the strings into an list of string numbers. The list is flattened, transformed into integers and collected into the final list.

[2, 3, 5, 6, 1, 0, 9, 5, 6, 3, 2, 1]

This is the output.

Java Stream map example V

In the next example, we use map operations on a list of user objects.

User.java
package com.zetcode;

public class User {

    private String name;
    private String occupation;

    public User(String name, String occupation) {
        this.name = name;
        this.occupation = occupation;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getOccupation() {
        return occupation;
    }

    public void setOccupation(String occupation) {
        this.occupation = occupation;
    }
}

This is the User class.

JavaStreamMapEx5.java
package com.zetcode;

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

public class JavaStreamMapEx5 {

    public static void main(String[] args) {

        var users = List.of(new User("Peter", "programmer"),
                new User("Jane", "accountant"), new User("Robert", "teacher"),
                new User("Milan", "programmer"), new User("Jane", "designer"));

        var userNames = users.stream().map(user -> user.getName()).sorted()
                .collect(Collectors.toList());
        System.out.println(userNames);

        var occupations = users.stream().map(user -> user.getOccupation())
                .sorted(Comparator.reverseOrder()).distinct()
                .collect(Collectors.toList());

        System.out.println(occupations);

    }
}

The example creates a list of sorted names from a list of users and a list of unique occupations in a reverse order.

[Jane, Jane, Milan, Peter, Robert]
[teacher, programmer, designer, accountant]

This is the output.

In this tutorial, we have have worked with Java Stream mapping operations. You might also be interested in the related tutorials: Java Streams, Java Stream reduce, Java Stream filter, Java 8 forEach tutorial, and Filtering a list in Java.