Java Language Streams Get a Slice of a Stream

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Example: Get a Stream of 30 elements, containing 21st to 50th (inclusive) element of a collection.

final long n = 20L; // the number of elements to skip
final long maxSize = 30L; // the number of elements the stream should be limited to
final Stream<T> slice = collection.stream().skip(n).limit(maxSize);

Notes:

  • IllegalArgumentException is thrown if n is negative or maxSize is negative
  • both skip(long) and limit(long) are intermediate operations
  • if a stream contains fewer than n elements then skip(n) returns an empty stream
  • both skip(long) and limit(long) are cheap operations on sequential stream pipelines, but can be quite expensive on ordered parallel pipelines


Got any Java Language Question?