Skip to content

Commit f772286

Browse files
tomekl007pivovarit
authored andcommitted
BAEL-669 test of an infinite stream (eugenp#1126)
* BAEL-669 test of an infinite stream * BAEL-699 example of custom type infinite stream * BAEL-699 do..while stream way * BAEL-669 generate stream of random uuids
1 parent 4aaefd3 commit f772286

2 files changed

Lines changed: 75 additions & 0 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.baeldung.stream;
2+
3+
4+
import java.util.stream.Stream;
5+
6+
public class InfiniteStreams {
7+
public static void main(String[] args) {
8+
doWhileOldWay();
9+
10+
doWhileStreamWay();
11+
12+
}
13+
14+
private static void doWhileOldWay() {
15+
16+
int i = 0;
17+
while (i < 10) {
18+
System.out.println(i);
19+
i++;
20+
}
21+
}
22+
23+
private static void doWhileStreamWay() {
24+
Stream<Integer> integers = Stream.iterate(0, i -> i + 1);
25+
integers.limit(10).forEach(System.out::println);
26+
}
27+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.baeldung.stream;
2+
3+
4+
import org.junit.Test;
5+
6+
import java.util.Arrays;
7+
import java.util.List;
8+
import java.util.Random;
9+
import java.util.UUID;
10+
import java.util.function.Supplier;
11+
import java.util.stream.Collectors;
12+
import java.util.stream.Stream;
13+
14+
import static org.junit.Assert.assertEquals;
15+
16+
public class InfiniteStreamTest {
17+
18+
@Test
19+
public void givenInfiniteStream_whenUseIntermediateLimitMethod_thenShouldTerminateInFiniteTime() {
20+
//given
21+
Stream<Integer> infiniteStream = Stream.iterate(0, i -> i + 2);
22+
23+
//when
24+
List<Integer> collect = infiniteStream
25+
.limit(10)
26+
.collect(Collectors.toList());
27+
28+
//then
29+
assertEquals(collect, Arrays.asList(0, 2, 4, 6, 8, 10, 12, 14, 16, 18));
30+
}
31+
32+
@Test
33+
public void givenInfiniteStreamOfRandomInts_whenUseLimit_shouldTerminateInFiniteTime() {
34+
//given
35+
Supplier<UUID> randomUUIDSupplier = UUID::randomUUID;
36+
Stream<UUID> infiniteStreamOfRandomUUID = Stream.generate(randomUUIDSupplier);
37+
38+
//when
39+
List<UUID> randomInts = infiniteStreamOfRandomUUID
40+
.skip(10)
41+
.limit(10)
42+
.collect(Collectors.toList());
43+
44+
//then
45+
assertEquals(randomInts.size(), 10);
46+
}
47+
48+
}

0 commit comments

Comments
 (0)