Fundamentals

Default Methods

Collections

Idioms and Techniques

Design Rationale

Advanced Questions

How can I get a stream with a number of repeated elements?

The best way is to use an integer range of the right size and map each int into an object of your choice. For example, to get a stream consisting of 20 copies of the string “x”, do the following:

IntStream.range(0, 20).mapToObj(i -> "x")

An alternative is to create a collection using Collections.nCopies and then stream that:

Collections.nCopies(5, "x").stream()

This is actually implemented using IntStream.range; however, it may be a bit more intuitive.