Java LongStream

1. Introduction

This tutorial focuses on the LongStream class in Java, which is part of the Stream API specifically designed for handling sequences of long primitive values. LongStream is used to perform aggregate operations efficiently on a sequence of long integers, which is often necessary for computations involving large data sets or where high-precision calculations are required.

Commonly Used Methods:

1. range() and rangeClosed() generate sequences of long integers.

2. sum(), average(), max(), and min() provide aggregation methods to compute statistics.

3. forEach() applies a given action to each element of the stream.

4. map() and filter() are used to transform and filter stream elements.

5. boxed() converts primitive long values to their corresponding wrapper class, Long.

2. Simple Example

In this section, we will write a Java program to demonstrate the commonly used LongStream class methods.

Program Steps

1. Generate a sequence of long integers.

2. Calculate statistical values such as sum, average, maximum, and minimum.

3. Utilize map and filter operations to modify stream contents.

4. Print results or convert the LongStream to other data structures.

Code Program

import java.util.OptionalDouble;
import java.util.OptionalLong;
import java.util.stream.LongStream;

public class LongStreamExample {

    public static void main(String[] args) {
        // Creating a LongStream from 1 to 10
        LongStream longNumbers = LongStream.rangeClosed(1, 10);

        // Calculating the sum of numbers
        long sum = longNumbers.sum();
        System.out.println("Sum of numbers from 1 to 10: " + sum);

        // Calculating the average of the numbers
        longNumbers = LongStream.rangeClosed(1, 10);
        OptionalDouble average = longNumbers.average();
        average.ifPresent(avg -> System.out.println("Average of numbers from 1 to 10: " + avg));

        // Finding the maximum and minimum value
        longNumbers = LongStream.rangeClosed(1, 10);
        OptionalLong max = longNumbers.max();
        max.ifPresent(m -> System.out.println("Maximum value: " + m));

        longNumbers = LongStream.rangeClosed(1, 10);
        OptionalLong min = longNumbers.min();
        min.ifPresent(m -> System.out.println("Minimum value: " + m));

        // Using filter and forEach to process elements
        longNumbers = LongStream.rangeClosed(1, 10);
        longNumbers.filter(n -> n % 2 == 0).forEach(n -> System.out.println("Even number: " + n));
    }
}

Output:

Sum of numbers from 1 to 10: 55
Average of numbers from 1 to 10: 5.5
Maximum value: 10
Minimum value: 1
Even number: 2
Even number: 4
Even number: 6
Even number: 8
Even number: 10

Explanation:

1. LongStream.rangeClosed(1, 10) creates a sequence of long integers from 1 to 10.

2. .sum() calculates the total sum of the integers in the stream.

3. .average() computes the average value, which is returned in an OptionalDouble to handle cases where the stream might be empty.

4. .max() and .min() find the highest and lowest values respectively, each returned as an OptionalLong.

5. The use of filter(n -> n % 2 == 0) and forEach() demonstrates how to process only even numbers within the stream.

3. Real-World Example

In this section, we will see the real-world example of Java's LongStream class, which analyzes financial transaction data in a large dataset. We will demonstrate how to calculate total transactions and average transaction value and identify high-value transactions using the LongStream methods, which are ideal for dealing with large numeric data types.

Program Steps

1. Simulate a stream of financial transaction data.

2. Calculate the total, average, maximum, and identify large transactions.

3. Print the results and specific transaction values for auditing purposes.

Code Program

import java.util.stream.LongStream;

public class FinancialTransactionAnalysis {

    public static void main(String[] args) {
        // Simulating a stream of transaction values (in cents to avoid floating point issues)
        LongStream transactions = LongStream.of(120000, 500000, 150000, 230000, 75000, 980000, 320000);

        // Calculating the total value of all transactions
        long totalTransactionsValue = transactions.sum();
        System.out.println("Total transactions value: $" + (totalTransactionsValue / 100.0));

        // Calculating the average transaction value
        transactions = LongStream.of(120000, 500000, 150000, 230000, 75000, 980000, 320000);
        transactions.average().ifPresent(avg -> System.out.println("Average transaction value: $" + (avg / 100.0)));

        // Finding the maximum transaction value
        transactions = LongStream.of(120000, 500000, 150000, 230000, 75000, 980000, 320000);
        transactions.max().ifPresent(max -> System.out.println("Maximum transaction value: $" + (max / 100.0)));

        // Filtering and printing transactions greater than $2000
        transactions = LongStream.of(120000, 500000, 150000, 230000, 75000, 980000, 320000);
        System.out.println("Transactions over $2000:");
        transactions.filter(value -> value > 200000)
                    .forEach(value -> System.out.println("$" + (value / 100.0)));
    }
}

Output:

Total transactions value: $2330.0
Average transaction value: $332.8571
Maximum transaction value: $9800.0
Transactions over $2000:
$5000.0
$2300.0
$9800.0
$3200.0

Explanation:

1. LongStream.of(...) initializes a stream with transaction values in cents.

2. .sum() aggregates all transaction values to compute the total.

3. .average() calculates the average transaction value, converting cents back to dollars for readability.

4. .max() finds the largest transaction in the dataset.

5. filter(value -> value > 200000) screens transactions to find those exceeding $2000, and forEach() is used to print these values.

Comments