IntStream and LongStream
Avoid boxing in streams.
Why Primitive Streams Exist
Stream<Integer> boxes every element into an Integer object. IntStream, LongStream, and DoubleStream work on raw primitives to avoid boxing overhead.
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
int sum = IntStream.of(1, 2, 3, 4).sum();
System.out.println(sum);
}
}Creating an IntStream
Use IntStream.of for explicit values, or Arrays.stream over an int[].
import java.util.Arrays;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
int[] data = {10, 20, 30};
IntStream s = Arrays.stream(data);
System.out.println(s.max().getAsInt());
}
}All lessons in this course
- IntStream and LongStream
- Range and Aggregate Operations
- Mapping to and from Object Streams
- Generating Primitive Streams