diff --git a/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java b/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java new file mode 100644 index 0000000000..097b516f8c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java @@ -0,0 +1,27 @@ +package com.baeldung.stream; + + +import java.util.stream.Stream; + +public class InfiniteStreams { + public static void main(String[] args) { + doWhileOldWay(); + + doWhileStreamWay(); + + } + + private static void doWhileOldWay() { + + int i = 0; + while (i < 10) { + System.out.println(i); + i++; + } + } + + private static void doWhileStreamWay() { + Stream integers = Stream.iterate(0, i -> i + 1); + integers.limit(10).forEach(System.out::println); + } +} diff --git a/core-java/src/test/java/com/baeldung/stream/InfiniteStreamTest.java b/core-java/src/test/java/com/baeldung/stream/InfiniteStreamTest.java new file mode 100644 index 0000000000..a1537a1735 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/stream/InfiniteStreamTest.java @@ -0,0 +1,48 @@ +package com.baeldung.stream; + + +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.Random; +import java.util.UUID; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; + +public class InfiniteStreamTest { + + @Test + public void givenInfiniteStream_whenUseIntermediateLimitMethod_thenShouldTerminateInFiniteTime() { + //given + Stream infiniteStream = Stream.iterate(0, i -> i + 2); + + //when + List collect = infiniteStream + .limit(10) + .collect(Collectors.toList()); + + //then + assertEquals(collect, Arrays.asList(0, 2, 4, 6, 8, 10, 12, 14, 16, 18)); + } + + @Test + public void givenInfiniteStreamOfRandomInts_whenUseLimit_shouldTerminateInFiniteTime() { + //given + Supplier randomUUIDSupplier = UUID::randomUUID; + Stream infiniteStreamOfRandomUUID = Stream.generate(randomUUIDSupplier); + + //when + List randomInts = infiniteStreamOfRandomUUID + .skip(10) + .limit(10) + .collect(Collectors.toList()); + + //then + assertEquals(randomInts.size(), 10); + } + +}