BAEL-669 test of an infinite stream (#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
This commit is contained in:
Tomasz Lelek 2017-02-12 10:22:25 +01:00 committed by Grzegorz Piwowarek
parent 4aaefd39df
commit f772286896
2 changed files with 75 additions and 0 deletions

View File

@ -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<Integer> integers = Stream.iterate(0, i -> i + 1);
integers.limit(10).forEach(System.out::println);
}
}

View File

@ -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<Integer> infiniteStream = Stream.iterate(0, i -> i + 2);
//when
List<Integer> 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<UUID> randomUUIDSupplier = UUID::randomUUID;
Stream<UUID> infiniteStreamOfRandomUUID = Stream.generate(randomUUIDSupplier);
//when
List<UUID> randomInts = infiniteStreamOfRandomUUID
.skip(10)
.limit(10)
.collect(Collectors.toList());
//then
assertEquals(randomInts.size(), 10);
}
}