Java Stream limit() Tutorial

beginner
20 min

Java Stream limit() Tutorial

Welcome to CodeYourCraft's Java Stream limit() tutorial! Today, we're going to explore the limit() function, an essential tool in Java Stream API. Let's dive in! šŸŽÆ

What is limit() in Java Stream?

limit() is a method in the Java Stream API that allows you to control the number of elements that will be processed further in the pipeline. It doesn't filter elements but simply limits the number of elements that are passed to downstream operations.

šŸ“ Note: The limit() function is often used with the sorted() method to get the top or bottom 'n' elements from a Stream.

Syntax

The syntax of limit() is as follows:

java
Stream<T> limit(long maxSize)
  • maxSize: The maximum number of elements you want to process.

Example 1: Basic Use Case

Let's consider an array of integers:

java
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

Now, let's create a Stream from this array and limit it to 5 elements using the limit() method:

java
Stream<Integer> stream = Stream.of(numbers).limit(5);

After executing the above code, the Stream will only contain the first 5 elements of the array:

[1, 2, 3, 4, 5]

Example 2: Real-world Application

Imagine you have a list of users, and you want to get the top 3 most active users. Here's how you can achieve that using limit() and sorted():

java
List<User> users = ... // Your list of users users.stream() .sorted(Comparator.comparing(User::getActivityCount).reversed()) .limit(3) .forEach(user -> System.out.println(user.getName()));

In this example, we first sort the list of users in descending order based on their activity count, then limit the stream to the top 3 users, and finally print their names.

Quiz

Quick Quiz
Question 1 of 1

What does the `limit()` function in Java Stream API do?

That's it for today! I hope you found this tutorial helpful. In the next lessons, we'll explore more Java Stream functions. Happy coding! šŸ’”