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! šÆ
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.
The syntax of limit() is as follows:
Stream<T> limit(long maxSize)maxSize: The maximum number of elements you want to process.Let's consider an array of integers:
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:
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]
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():
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.
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! š”