Java IntStream

1. Introduction

This tutorial introduces the IntStream class from the Java Stream API, which is designed to handle sequences of primitive int values efficiently. This specialized stream is useful for performing numeric operations, such as summing numbers, finding statistics, or performing element-wise transformations.

Commonly Used Methods:

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

2. sum(), average(), max(), and min() provide basic statistical calculations.

3. forEach() processes each element sequentially.

4. map() transforms each element of the stream.

5. filter() excludes elements based on a predicate.

6. boxed() converts primitive int values to their Integer object equivalents.

2. Simple Example

Program Steps

1. Generate a sequence of integers using range() or rangeClosed().

2. Apply statistical methods to perform calculations.

3. Use map(), filter(), and forEach() for transformations and processing.

4. Convert IntStream to Stream<Integer> using boxed().

Code Program

import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.stream.IntStream;

public class IntStreamExample {

    public static void main(String[] args) {
        // Generating an IntStream from 1 to 10
        IntStream numbers = IntStream.rangeClosed(1, 10);

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

        // Finding the average of the numbers
        IntStream numbersForAverage = IntStream.rangeClosed(1, 10);
        OptionalDouble average = numbersForAverage.average();
        average.ifPresent(avg -> System.out.println("Average of 1 to 10: " + avg));

        // Finding the maximum and minimum
        IntStream numbersForMax = IntStream.rangeClosed(1, 10);
        OptionalInt max = numbersForMax.max();
        max.ifPresent(m -> System.out.println("Maximum of 1 to 10: " + m));

        IntStream numbersForMin = IntStream.rangeClosed(1, 10);
        OptionalInt min = numbersForMin.min();
        min.ifPresent(m -> System.out.println("Minimum of 1 to 10: " + m));

        // Filtering even numbers and printing them
        IntStream numbersForFilter = IntStream.rangeClosed(1, 10);
        numbersForFilter.filter(n -> n % 2 == 0).forEach(n -> System.out.println("Filtered even number: " + n));

        // Mapping and collecting to list
        IntStream numbersForMap = IntStream.rangeClosed(1, 5);
        numbersForMap.map(n -> n * n).forEach(n -> System.out.println("Square of number: " + n));
    }
}

Output:

Sum of 1 to 10: 55
Average of 1 to 10: 5.5
Maximum of 1 to 10: 10
Minimum of 1 to 10: 1
Filtered even number: 2
Filtered even number: 4
Filtered even number: 6
Filtered even number: 8
Filtered even number: 10
Square of number: 1
Square of number: 4
Square of number: 9
Square of number: 16
Square of number: 25

Explanation:

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

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

3. .average() computes the average of the numbers, returning an OptionalDouble.

4. .max() and .min() find the maximum and minimum values in the stream, respectively, returning OptionalInt.

5. .filter(n -> n % 2 == 0) filters the stream to include only even numbers, which are then processed with .forEach().

6. .map(n -> n * n) transforms each number by squaring it, demonstrating the use of map() for arithmetic operations.

3. Real-World Example

In this section, we use the Java Stream API's IntStream class to analyze financial data—specifically, the monthly expenditures of a business. We will perform various calculations, such as total expenditure for the year and average monthly spending, and identify peak spending months using methods provided by IntStream.

Program Steps

1. Define an array of monthly expenditures.

2. Calculate the total expenditure for the year.

3. Determine the average, maximum, and minimum monthly spending.

4. Identify months with spending above a certain threshold.

Code Program

import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.stream.IntStream;

public class FinancialAnalysis {

    public static void main(String[] args) {
        // Monthly expenditures in thousands of dollars
        int[] monthlyExpenditures = {12, 18, 15, 14, 20, 13, 12, 16, 19, 22, 21, 17};

        // Total annual expenditure
        int totalExpenditure = IntStream.of(monthlyExpenditures).sum();
        System.out.println("Total expenditure for the year: $" + totalExpenditure + "K");

        // Average monthly expenditure
        OptionalDouble averageExpenditure = IntStream.of(monthlyExpenditures).average();
        averageExpenditure.ifPresent(avg -> System.out.println("Average monthly expenditure: $" + avg + "K"));

        // Maximum and minimum expenditure
        OptionalInt maxExpenditure = IntStream.of(monthlyExpenditures).max();
        maxExpenditure.ifPresent(max -> System.out.println("Maximum monthly expenditure: $" + max + "K"));

        OptionalInt minExpenditure = IntStream.of(monthlyExpenditures).min();
        minExpenditure.ifPresent(min -> System.out.println("Minimum monthly expenditure: $" + min + "K"));

        // Months with expenditures exceeding $18K
        System.out.println("Months with expenditures exceeding $18K:");
        IntStream.range(0, monthlyExpenditures.length)
                 .filter(i -> monthlyExpenditures[i] > 18)
                 .forEach(i -> System.out.println("Month " + (i + 1) + ": $" + monthlyExpenditures[i] + "K"));
    }
}

Output:

Total expenditure for the year: $204K
Average monthly expenditure: $17.0K
Maximum monthly expenditure: $22K
Minimum monthly expenditure: $12K
Months with expenditures exceeding $18K:
Month 2: $18K
Month 5: $20K
Month 9: $19K
Month 10: $22K
Month 11: $21K

Explanation:

1. IntStream.of(monthlyExpenditures) creates an IntStream from an array of monthly expenditure values.

2. .sum() computes the total annual expenditure from the stream.

3. .average() calculates the average monthly expenditure.

4. .max() and .min() find the highest and lowest monthly expenditures, respectively.

5. IntStream.range(0, monthlyExpenditures.length).filter(...) iterates over the index of the expenditures to identify specific months where spending exceeded $18K, demonstrating how to combine range() with filter() and forEach() for conditional processing.

Comments