Java LongStream: A Practical Guide to Primitive Streams
Learn how to create and use Java LongStream for primitive long operations, including creation, common operations, performance considerations, and when to choose it over Stream<Long>.

Java LongStream is a specialized stream type for primitive long values. It is part of the java.util.stream package and provides a way to process sequences of longs without boxing each value into a Long object. This article covers how to create and use LongStream effectively, including common operations, performance implications, and when it is a better choice than Stream<Long>.
Creating a LongStream
LongStream can be created from several sources. The most common are range and rangeClosed, which generate a sequence of longs from a start (inclusive) to an end (exclusive or inclusive respectively).
LongStream range = LongStream.range(1, 10); // 1..9
LongStream closedRange = LongStream.rangeClosed(1, 10); // 1..10You can also create a stream from an array or individual values using of:
LongStream fromArray = LongStream.of(3L, 5L, 8L, 13L);
LongStream single = LongStream.of(42L);The iterate method generates an infinite stream by applying a unary operator repeatedly. It is often used with limit to bound the number of elements:
LongStream powersOfTwo = LongStream.iterate(1L, n -> n * 2).limit(10);Finally, concat merges two streams into one. This is useful when you need to process disjoint ranges together.
LongStream combined = LongStream.concat(LongStream.range(1, 5), LongStream.range(10, 15));Core Operations: Mapping, Filtering, and Reducing
LongStream supports the same functional operations as Stream<T>, but with primitive-specialized versions. For example, map takes a LongUnaryOperator and returns a new LongStream:
LongStream squares = LongStream.range(1, 10).map(n -> n * n);Filtering uses LongPredicate:
LongStream evens = LongStream.range(1, 20).filter(n -> n % 2 == 0);Reduction operations like sum, min, max, and average are terminal. sum returns a long; min and max return OptionalLong; and average returns OptionalDouble. The reduce method gives you full control over accumulation:
long total = LongStream.range(1, 100).reduce(0L, (a, b) -> a + b);To collect into a collection, use boxed() to convert to Stream<Long>, then apply collect. This is necessary because LongStream does not have the collect(Collector) convenience method that object streams have.
List<Long> list = LongStream.range(1, 10).boxed().collect(Collectors.toList());Performance Considerations: Primitive vs Boxed Streams
Using LongStream avoids the boxing and unboxing required by Stream<Long>. With Stream<Long>, each element is a Long object, which adds allocation and garbage-collection pressure. LongStream operates on raw long values directly, so in tight numeric loops or large pipelines the difference can be significant, but actual results depend on the JVM, the data size, and the operations. Measure before assuming a specific speedup.
For example, summing one million longs with Stream<Long> would require boxing each value before it enters the pipeline. A LongStream keeps the values as primitive longs throughout. The benefit is most likely to be visible when the stream is large and the per-element operations are simple.
Parallel execution can also help, but using LongStream does not guarantee that parallel() will be faster. The parallel() method changes how the stream is split and processed, so benchmark your own workload before adding or removing it.
Handling Edge Cases and Parallel Streams
An empty LongStream is valid and can be created with LongStream.empty(). Terminal operations like sum return 0, count returns 0, and min/max return an OptionalLong that is empty. If you use the reduce overload with an identity value, that identity is the result for an empty stream.
Overflow is a real concern when working with longs. Operations like sum can overflow silently, producing a negative result. If your data may exceed Long.MAX_VALUE, consider using BigInteger or checking for overflow explicitly. The stream API does not provide overflow detection.
Parallel streams can improve throughput on multi-core machines, but they add overhead for small streams. A rule of thumb is to use parallel() only when the stream has many elements and the per-element computation is nontrivial. For simple operations on a few hundred elements, sequential execution is usually faster.
LongStream vs Stream<Long>: When to Use Which
The choice between LongStream and Stream<Long> depends on the context. The table below summarizes the key differences.
| Aspect | LongStream | Stream<Long> |
|---|---|---|
| Element type | long (primitive) | Long (object) |
| Memory footprint | Lower (no boxing) | Higher (boxing overhead) |
| Performance | Potentially lower for numeric pipelines | Extra boxing/unboxing cost on numeric data |
| Collectors | Not directly supported | Full Collector support |
| Optional results | OptionalLong | Optional<Long> |
| Best for | Numeric computations, ranges | When you need to collect or use complex collectors |
Use LongStream when you are processing a large set of primitive longs and performance matters. Use Stream<Long> when you need to collect into a complex structure, use custom collectors, or when the data is already boxed and the volume is small.
A Practical Example: Processing Large Ranges
Suppose you need to find the sum of all even numbers from 1 to 10 million. Using LongStream, you can write a concise and efficient pipeline:
long sum = LongStream.rangeClosed(1, 10_000_000)
.filter(n -> n % 2 == 0)
.sum();This avoids creating millions of Long objects. If you also need to compute statistics like average, you can use summaryStatistics():
LongSummaryStatistics stats = LongStream.rangeClosed(1, 10_000_000)
.filter(n -> n % 2 == 0)
.summaryStatistics();
System.out.println("Count: " + stats.getCount());
System.out.println("Sum: " + stats.getSum());For parallel processing, simply add .parallel() before the terminal operation. This may reduce runtime on machines with many cores if the operation is CPU-bound and the stream is large enough to justify the overhead.
long sumParallel = LongStream.rangeClosed(1, 10_000_000)
.parallel()
.filter(n -> n % 2 == 0)
.sum();When working with very large ranges, be mindful of the range vs rangeClosed boundary and the potential for overflow in intermediate calculations. These details matter more with primitive streams because there is no object wrapper to hide arithmetic issues.
Try matching browser tools
All toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesJava Final Keyword: Usage and Behavior
How Java's final keyword works for variables, methods, and classes, with practical examples and decision guidance for using it.
Java Final Variable: Syntax, Behavior, and Use Cases
Understand what a final variable in Java means, how initialization works, and when to use it for constants, immutability, and clearer code.
Java Duration vs Period: When to Use Each
java duration vs period: Compare Java Duration and Period to handle time-based and date-based calculations correctly. Learn syntax, conversion, and pitfalls.
Instance vs Static Variables in Java: Key Differences
Understand the difference between instance and static variables in Java, including memory, lifecycle, and when to use each.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.