-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathstream-iterate-predicate.yaml
More file actions
49 lines (49 loc) · 1.56 KB
/
stream-iterate-predicate.yaml
File metadata and controls
49 lines (49 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
---
id: 37
slug: "stream-iterate-predicate"
title: "Stream.iterate() with predicate"
category: "streams"
difficulty: "intermediate"
jdkVersion: "9"
oldLabel: "Java 8"
modernLabel: "Java 9+"
oldApproach: "iterate + limit"
modernApproach: "iterate(seed, pred, op)"
oldCode: |-
Stream.iterate(1, n -> n * 2)
.limit(10)
.forEach(System.out::println);
// can't stop at a condition
modernCode: |-
Stream.iterate(
1,
n -> n < 1000,
n -> n * 2
).forEach(IO::println);
// stops when n >= 1000
summary: "Use a predicate to stop iteration — like a for-loop in stream form."
explanation: "The three-argument Stream.iterate(seed, hasNext, next) works like a\
\ for-loop: seed is the start, hasNext determines when to stop, and next produces\
\ the next value."
whyModernWins:
- icon: "🎯"
title: "Natural termination"
desc: "Stop based on a condition, not an arbitrary limit."
- icon: "📐"
title: "For-loop equivalent"
desc: "Same semantics as for(seed; hasNext; next)."
- icon: "🛡️"
title: "No infinite stream risk"
desc: "The predicate guarantees termination."
support:
state: "available"
description: "Widely available since JDK 9 (Sept 2017)"
prev: "streams/stream-of-nullable"
next: "streams/stream-takewhile-dropwhile"
related:
- "streams/virtual-thread-executor"
- "streams/optional-or"
- "streams/optional-ifpresentorelse"
docs:
- title: "Stream.iterate()"
href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/stream/Stream.html#iterate(T,java.util.function.Predicate,java.util.function.UnaryOperator)"