Introduction

In java, we can convert a specific set into a stream, so in some cases, such as in a test environment, we need to construct a stream with a certain number of elements, how do we need to handle it?

Here we can construct an unlimited stream and then call the limit method to limit the number returned.

Basic use

Let’s start with an example of using Stream.iterate to create an infinite Stream.

 1 2 3 4 5 6 7 8   @Test public void infiniteStream(){ Stream infiniteStream = Stream.iterate(0, i -> i + 1); List collect = infiniteStream .limit(10) .collect(Collectors.toList()); log.info("{}",collect); } 

In the above example, we created an infinite stream of 0, 1, 2, 3, 4 …. by calling Stream.iterate method. of an infinite stream.

Then call limit(10) to get the first 10 of them. Finally, the collect method is called to convert it into a collection.

Look at the following output.

 1  INFO com.javaisland.InfiniteStreamUsage - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 

Custom types

What do we do if we want to output a collection of custom types?

First, we define a custom type.

 1 2 3 4 5  @Data @AllArgsConstructor public class IntegerWrapper { private Integer integer; } 

This custom type is then created using Stream.generate’s generator: the

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15   public static IntegerWrapper generateCustType(){ return new IntegerWrapper(new Random().nextInt(100)); } @Test public void infiniteCustType(){ Supplier randomCustTypeSupplier = InfiniteStreamUsage::generateCustType; Stream infiniteStreamOfCustType = Stream.generate(randomCustTypeSupplier); List collect = infiniteStreamOfCustType .skip(10) .limit(10) .collect(Collectors.toList()); log.info("{}",collect); } 

Look at the output.

 1  INFO com.javaisland.InfiniteStreamUsage - [IntegerWrapper(integer=46), IntegerWrapper(integer=42), IntegerWrapper(integer=67), IntegerWrapper(integer=11), IntegerWrapper(integer=14), IntegerWrapper(integer=80), IntegerWrapper(integer=15), IntegerWrapper(integer =19), IntegerWrapper(integer=72), IntegerWrapper(integer=41)]