Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

LongStream — creating and summing a stream of long values

LongStream processes primitive long values rather than Long objects. LongStream.of creates a stream from supplied values, and LongStream.sum completes processing and returns their sum as a long.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

LongStream.of(long t)
LongStream.of(long... values)
long sum = LongStream.of(10L, 20L, 30L).sum();

java.util.stream.LongStream is the stream specialization for primitive long values, unlike Stream<Long>, which contains wrapper objects. A stream describes element processing rather than a collection that stores data.

LongStream.of(long t) creates a sequential stream containing one element. The overload LongStream.of(long... values) creates a sequential, ordered stream from the supplied arguments or a long[] array. Calling LongStream.of() creates an empty stream.

LongStream.sum, invoked as .sum(), is a terminal operation returning a long. It is equivalent to the reduction reduce(0, Long::sum), so an empty stream returns 0. Intermediate operations are lazy; a terminal operation initiates processing. After it completes, do not reuse the same stream — create a new one for another calculation.

The example sums 10L, 20L, and 30L, then prints 60. The documentation covers Java SE 21, which is also the repository runtime. The production runtime has not been attested.

Examples

import java.util.stream.LongStream;

public class Main {
    public static void main(String[] args) {
        long total = LongStream.of(10L, 20L, 30L).sum();
        System.out.println(total);
    }
}

Result

60

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources