Junior
What is the purpose of the limit() method in streams?
sobes.tech AI
Answer from AI
The limit(long maxSize) method in Java Stream API is designed to create a new stream containing elements from the original stream, up to a maximum of maxSize. It is an intermediate operation that discards remaining elements after the specified number has been processed.
Main effects:
- Size limitation: Applies a limit to the maximum number of elements in the resulting stream.
- Laziness: Element computation occurs only when they are actually requested by a terminal operation, up to the specified limit.
- Truncation capability: If the original stream contains more elements than specified in
maxSize, the stream will be truncated tomaxSizeelements. If fewer, all available elements are used.
Example usage:
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Eve");
List<String> firstTwoNames = names.stream()
.limit(2) // Limit the stream to the first two elements
.collect(Collectors.toList()); // Collect into a list
// firstTwoNames will contain ["Alice", "Bob"]