Sobes.tech
Junior — Middle

Kuidas saab Java Streamis töötavate elementide arvu piirata?

sobes.tech AI

Vastus AI-lt

In the Java Stream API, to limit the number of elements processed in a stream, you can use the following methods:

  • limit(n) — limits the stream to the first n elements.
  • skip(n) — skips the first n elements and starts processing from the (n+1)-th.

Example of usage:

List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6);
List<Integer> limited = numbers.stream()
    .limit(3) // will take only the first 3 elements
    .collect(Collectors.toList());

System.out.println(limited); // [1, 2, 3]

It can also be combined with filtering or other operations for more precise control over the number of processed elements.