Building an infinite stream in java 8

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.

    @Test
    public void infiniteStream(){
        Stream<Integer> infiniteStream = Stream.iterate(0, i -> i + 1);
        List<Integer> 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.

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.

@Data
@AllArgsConstructor
public class IntegerWrapper {
    private Integer integer;
}

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

    public static IntegerWrapper generateCustType(){
        return new IntegerWrapper(new Random().nextInt(100));
    }

    @Test
    public void infiniteCustType(){
        Supplier<IntegerWrapper> randomCustTypeSupplier = InfiniteStreamUsage::generateCustType;
        Stream<IntegerWrapper> infiniteStreamOfCustType = Stream.generate(randomCustTypeSupplier);

        List<IntegerWrapper> collect = infiniteStreamOfCustType
                .skip(10)
                .limit(10)
                .collect(Collectors.toList());
        log.info("{}",collect);
    }

Look at the output.

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)]

Summary

This article presents two examples of generating infinite streams.