Java 8 IntStream Examples




In Java, `IntStream` is a part of the java.util.stream package and represents a stream of primitive integers. It's designed to work with the functional programming features introduced in Java 8, allowing you to perform aggregate operations on sequences of elements. Here are some examples of using `IntStream`:

Example 1: Creating IntStream


import java.util.stream.IntStream;

public class IntStreamExample {
    public static void main(String[] args) {
        // Create an IntStream using range
        IntStream.range(1, 6).forEach(System.out::println); // Prints 1, 2, 3, 4, 5
        
        // Create an IntStream using rangeClosed
        IntStream.rangeClosed(1, 5).forEach(System.out::println); // Prints 1, 2, 3, 4, 5
    }
}

Example 2: Operations on IntStream


import java.util.stream.IntStream;

public class IntStreamExample {
    public static void main(String[] args) {
        // Sum of elements
        int sum = IntStream.range(1, 6).sum(); // sum = 15
        
        // Find the maximum element
        int max = IntStream.of(3, 1, 4, 1, 5, 9, 2, 6).max().orElse(0); // max = 9
        
        // Filter and print even numbers
        IntStream.range(1, 6)
                 .filter(n -> n % 2 == 0)
                 .forEach(System.out::println); // Prints 2, 4
    }
}

Example 3: Mapping with IntStream


import java.util.stream.IntStream;

public class IntStreamExample {
    public static void main(String[] args) {
        // Map each element to its square
        IntStream.range(1, 6)
                 .map(n -> n * n)
                 .forEach(System.out::println); // Prints 1, 4, 9, 16, 25
    }
}

Example 4: IntStream to Array


import java.util.stream.IntStream;

public class IntStreamExample {
    public static void main(String[] args) {
        // Convert IntStream to array
        int[] array = IntStream.range(1, 6).toArray(); // array = {1, 2, 3, 4, 5}
    }
}

Example 5: IntStream with Reduction


import java.util.stream.IntStream;

public class IntStreamExample {
    public static void main(String[] args) {
        // Use reduce to get the product of elements
        int product = IntStream.range(1, 6)
                               .reduce((x, y) -> x * y)
                               .orElse(1); // product = 120
    }
}

These examples cover a range of basic operations that you can perform using `IntStream` in Java. Remember that `IntStream` is part of the broader Java Stream API, and similar operations can be performed on streams of other types (e.g., `DoubleStream`, `LongStream`).



Post a Comment

Previous Post Next Post