how to use IntStream in java ?
时间: 2024-05-04 11:20:16 浏览: 9
`IntStream` is a Java 8 feature that allows you to create a stream of primitive integers. Here's an example of how to use `IntStream`:
```java
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
// Create an IntStream from an array of integers
int[] numbers = { 1, 2, 3, 4, 5 };
IntStream stream1 = IntStream.of(numbers);
// Create an IntStream from a range of integers
IntStream stream2 = IntStream.range(1, 6); // 1, 2, 3, 4, 5
// Create an IntStream from a range of integers with a step
IntStream stream3 = IntStream.iterate(0, n -> n + 2).limit(5); // 0, 2, 4, 6, 8
// Print the elements of the streams
stream1.forEach(System.out::println);
stream2.forEach(System.out::println);
stream3.forEach(System.out::println);
}
}
```
The `IntStream` class has many other methods that you can use to perform operations on the stream, such as `filter()`, `map()`, `reduce()`, and `sum()`. You can also convert an `IntStream` to an array, list, or set using the `toArray()`, `boxed()`, or `collect()` methods.