Java 8 Stream limit method example.
The Stream.limit() method returns a Stream with elements of the source stream, truncated to be no longer than the specified size.
While limit() is generally a cheap operation on sequential stream pipelines, it can be quite expensive on
ordered parallel pipelines, especially for large values of maxSize, since limit(n) is constrained to return not just any
n elements, but the first n elements in the encounter order. Using an unordered stream source (such as generate(Supplier))
or removing the ordering constraint with BaseStream.unordered() may result in significant speedups of limit() in parallel
pipelines, if the semantics of your situation permit. If consistency with encounter order is required, and you are experiencing
poor performance or memory utilization with limit() in parallel pipelines, switching to sequential execution with
BaseStream.sequential() may improve performance.
package com.java2novice.streams;
import java.util.UUID;
import java.util.stream.Stream;
public class StreamLimitEx {
public static void main(String a[]) {
Stream.of("bus", "car", "bicycle", "flight", "train").limit(3).forEach(System.out::println);
System.out.println("--------------------------------");
Stream.generate(UUID::randomUUID).limit(10).forEach(System.out::println);
}
}
|
|