Java.Java8.What is the limit() method for in streams?

The limit() method is a handy tool in the Java Stream API that lets you restrict the number of elements flowing through a stream.


✅ What is limit() in Streams?

Stream<T> limit(long maxSize)

📌 Purpose:

  • Truncates the stream to contain no more than maxSize elements
  • Returns a new Stream with the first n elements
  • Works with ordered streams (like List, SortedSet, etc.)

🧠 Simple Example:

Stream.of("one", "two", "three", "four")
      .limit(2)
      .forEach(System.out::println);

// Output:
// one
// two

🔧 Real Use Cases

✅ 1. Paginate results (e.g., first 10 items)

List<String> names = List.of("Anna", "Bob", "Charlie", "David", "Eve");

names.stream()
     .limit(3)
     .forEach(System.out::println); // Output: Anna, Bob, Charlie

✅ 2. Limit infinite streams

Stream<Integer> infinite = Stream.iterate(0, n -> n + 1);

infinite
    .limit(5)
    .forEach(System.out::println); // Output: 0 1 2 3 4

⚠️ Without limit(), infinite streams would run forever.

🔄 Common Pairing: skip(n) + limit(n)

Use together for pagination:

List<String> data = List.of("a", "b", "c", "d", "e", "f");

data.stream()
    .skip(2)        // Skip first 2
    .limit(3)       // Take next 3
    .forEach(System.out::println); // Output: c, d, e

✅ Summary

Methodlimit(long maxSize)
💡 PurposeRestricts a stream to the first N elements
🧠 Use CaseTrimming results, pagination, controlling infinite streams
💡 LazinessIt’s an intermediate operation — doesn’t execute immediately
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.