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.
Code
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
SemVer Range CheckerCheck whether a semantic version satisfies an npm-style range such as caret, tilde, comparison sets, wildcards, or hyphen ranges.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.