stream.limit() method in Java
Prerequisite : Streams in Java8
The limit(long N) is a method of java.util.stream.Stream object. This method takes one (long N) as an argument and returns a stream of size no more than N. limit() can be quite expensive on ordered parallel pipelines, if the value of N is large, because limit(N) is constrained to return the first N elements in the encounter order and not just any n elements.
Syntax :
Stream<T> limit(long N)
Where N is the number of elements the stream should be
limited to and this function returns new stream as output.
Exception : If the value of N is negative, then IllegalArgumentException is thrown by the function.
Below are some examples to understand the implementation of the function in a better way.
Example 1 :
import java.util.*;
class GFG {
public static void main(String[] args)
{
List<Integer> list = new ArrayList<Integer>();
list.add(- 2 );
list.add( 0 );
list.add( 2 );
list.add( 4 );
list.add( 6 );
list.add( 8 );
list.add( 10 );
list.add( 12 );
list.add( 14 );
list.add( 16 );
int limit = 4 ;
int count = 0 ;
Iterator<Integer> it = list.iterator();
while (it.hasNext()) {
it.next();
count++;
if (count > limit) {
it.remove();
}
}
System.out.print( "New stream of length N"
+ " after truncation is : " );
for (Integer number : list) {
System.out.print(number + " " );
}
}
}
|
Output :
New stream of length N after truncation is : -2 0 2 4
Application :
import java.util.stream.Stream;
import java.util.ArrayList;
import java.util.List;
class gfg{
public static Stream<String> limiting_func(Stream<String> ss, int range){
return ss.limit(range);
}
public static void main(String[] args){
List<String> arr = new ArrayList<>();
arr.add( "geeks" );
arr.add( "for" );
arr.add( "geeks" );
arr.add( "computer" );
arr.add( "science" );
Stream<String> str = arr.stream();
Stream<String> lm = limiting_func(str, 3 );
lm.forEach(System.out::println);
}
}
|
Output :
geeks
for
geeks
Last Updated :
06 Dec, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...