Java Stream mapToLong Example

1. Introduction

In this tutorial, we will learn how to use the mapToLong() method of the Java Stream API. mapToLong() is used to convert objects within a stream into long values, facilitating operations that require long integers, such as handling large numbers or performing aggregate calculations over a range of values.

Key Points

1. mapToLong() transforms each element of the stream into a long using a provided function that returns a long type.

2. It results in a LongStream, allowing for operations specifically optimized for the long data type.

3. This method is essential for processing streams where the elements represent or can be converted into large numeric values.

2. Program Steps

1. Create a Stream of elements.

2. Apply mapToLong() to transform these elements into long values.

3. Perform operations such as summing, finding averages, or other relevant calculations on the resulting LongStream.

3. Code Program

import java.util.stream.Stream;

public class StreamMapToLongExample {

    public static void main(String[] args) {
        // Stream of product prices represented as strings
        Stream<String> priceStrings = Stream.of("100000", "200000", "300000");

        // Converting string prices to long values and calculating their sum
        long totalRevenue = priceStrings.mapToLong(Long::parseLong).sum();
        System.out.println("Total revenue: " + totalRevenue);
    }
}

Output:

Total revenue: 600000

Explanation:

1. Stream.of("100000", "200000", "300000") creates a stream of strings where each string represents a large numeric value, typically simulating prices or costs.

2. priceStrings.mapToLong(Long::parseLong) converts each string to a long using Long.parseLong, which is necessary to handle large numbers that exceed the range of int.

3. .sum() computes the sum of these long values in the resulting LongStream, aggregating the total revenue.

Comments