IntStream Range Iterate Sequences

Generate numeric pipelines with IntStream.range and iterate, mixing primitive sum with boxed collectors and index-based array access in one pass.

JavaData Integrity

Code

snippet
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class SequencePipes {

    public static void main(String[] args) {
        // rangeClosed 双闭区间直接求和:原始流不装箱
        System.out.println("sum 1..100 = " + IntStream.rangeClosed(1, 100).sum());

        // iterate 生成无限序列,limit 截断后转成 List
        List<Integer> powers = IntStream.iterate(1, i -> i * 2)
                .limit(10)
                .boxed()
                .collect(Collectors.toList());
        System.out.println("powers of two: " + powers);

        // mapToObj 把原始流映射成对象流再拼接
        String ruler = IntStream.range(0, 12)
                .mapToObj(i -> i % 3 == 0 ? "|" : "-")
                .collect(Collectors.joining());
        System.out.println("ruler: " + ruler);

        // range 是按下标处理数组的安全惯用法
        int[] readings = {18, 21, 19, 24};
        int evenIndexTotal = IntStream.range(0, readings.length)
                .filter(i -> i % 2 == 0)
                .map(i -> readings[i])
                .sum();
        System.out.println("even-index total = " + evenIndexTotal);
    }
}

What the code does

IntStream Range Iterate Sequences keeps everything in the class SequencePipes and the function main.

The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable.

Using it

Running the file prints labeled results such as sum 1..100 =, powers of two:, ruler: — each operation’s effect is visible in the output.

Key statements

.collect(Collectors.joining());
.collect(Collectors.toList());
.filter(i -> i % 2 == 0)
.map(i -> readings[i])
.sum();

Interactive Tools for This Topic

FAQ

What does IntStream Range Iterate Sequences print when run?
Run it as a complete program — the output lines carry labels such as `sum 1..100 =`, `powers of two:`, `ruler:`.