1. Overview
In this article, you'll learn how to limit the stream elements to the given size even though it has more elements.
Use Java 8 Stream.limit() method to retrieve only the first n objects and setting the maximum size. And it ignores the remaining values after size n. Stream.limit(long maxSize) returns a Stream of objects.
We will explore the different ways to do limit the stream using the limit() method and how to limit the collection elements based on a condition?
2. Java 8 Strem limit() Syntax
The following is the syntax from the Stream API.
Stream<T> limit(long maxSize)
Takes the maxSize long value that is a number of objects should be limited and take from the top of the stream. Returns a Stream containing only n elements from the stream.
3. Java 8 Stream limit Rules
Here are the more points about the limit() method.
3.1 This is an intermediate operation.
3.2 This is a good choice when working with infinite streams or infinite values.
3.3 limit() method is invoked after calling the terminal operation such as count() or collect() methods.
3.4 This returns a stream of elements with the size or max limit given.
3.5 This works well in sequential streams.
3.6 Not suggested using in the parallel streams such as larger or higher in size.
3.7 Using an unordered stream source (such as generate(Supplier)) or removing the ordering constraint with BaseStream.unordered() may result in significant speedups of limit() in parallel pipelines.
3.8 maxSize can not be negative. If negative then it will throw IllegalArgumentException.
3.9 Retured stream picks the elemtns from the previous intermediate operation such as map() or filter() methods output as how they appear in the sequential order.
4. Stream limit() Example 1
First, for example, to get only the first 5 values from List.
package limit;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Java8StreamLimitExample1 {
public static void main(String[] args) {
// creating list
List<Integer> numbers = new ArrayList<>();
// adding values to list
numbers.add(10);
numbers.add(20);
numbers.add(40);
numbers.add(60);
numbers.add(20);
numbers.add(-1000);
numbers.add(-87);
numbers.add(4);
numbers.add(343);
numbers.add(23);
numbers.add(343);
numbers.add(1454);
numbers.add(1464);
numbers.add(10);
// Converting list to stream
Stream<Integer> stream = numbers.stream();
// Taking only first 10 values from stream and converting them into list
List<Integer> limit10 = stream.limit(10).collect(Collectors.toList());
// printing the limit output
System.out.println("Limit output with 10 values: ");
limit10.forEach(value -> System.out.println(value));
}
}
Limit output with 10 values: 10 20 40 60 20 -1000 -87 4 343 23
5. Stream limit() Example 2
Next Example to limit the objects to 5 from the infinite stream of powers of number 2 and collected output into Set.
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Java8StreamLimitExample2 {
public static void main(String[] args) {
// Creating a Stream with 2 powers.
Stream<Integer> infiniteNumbers = Stream.iterate(2, i -> i * 2);
// Limiting 2 powers to first 5 values and converting it to Set.
Set<Integer> limit10 = infiniteNumbers.limit(5).collect(Collectors.toSet());
// printing the set values.
System.out.println("Limit output with 5 : ");
limit10.forEach(value -> System.out.println(value));
}
}
Output:
Limit output with 5 : 16 32 2 4 8
6. Stream limit() Example 3 - Condition Based
Example to limit the collection size based on a condition. Even you can use the Predicate for condition-based filtering the limit.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class StreamLimitExampleCondition {
public static void main(String[] args) {
// Creating List using Arrays.asList() method
List<String> list = new ArrayList<String>(Arrays.asList("one", "two", "four", "five", "six"));
System.out.println("Original list before : " + list);
// Get max 2 objects by limit
int maxLimit = 2;
// comparator creation
Comparator<String> comp = (String::compareTo);
// reverse sorting
Comparator<String> comparator = comp.reversed();
// limit offset based on limit.
List<String> newList = list.stream().sorted(comparator).limit(maxLimit > 0 ? maxLimit : list.size())
.collect(Collectors.toList());
// printing the condition offset output
System.out.println("limiting to 2 after sorting : " + newList);
}
}
Original list before : [one, two, four, five, six] limiting to 2 after sorting : [two, six]
7. Stream limit() Example 4 before Java 8
import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class StreamLimitExampleBeforeJava8 { public static void main(String[] args) { // Creating List using Arrays.asList() method List<String> strings = new ArrayList<String>(Arrays.asList("java 8", "programs", "on", "javaprogram.com", "new", "blog")); System.out.println("Original list before limit logic " + strings); // creating iterator object Iterator<String> it = strings.iterator(); // creating limit and current index. int limit = 3; int index = 0; // Iterating the iterator while (it.hasNext()) { // Moving the iterator point to the next element. If you comment this line the it will give java.lang.IllegalStateException. it.next(); index++; // checking the current index is higher than limit. if (index > limit) { it.remove(); } } System.out.println("After limiting to 5 strings : "+strings); } }
Original list before limit logic [java 8, programs, on, javaprogram.com, new, blog] After limiting to 5 strings : [java 8, programs, on]
No comments:
Post a Comment
Please do not add any spam links in the comments section.