The Wayback Machine - https://web.archive.org/web/20241004140142/https://www.geeksforgeeks.org/stream-limit-method-in-java/
Open In App

stream.limit() method in Java

Last Updated : 27 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 :

Java
// Java code to show implementation
// of limit() function
import java.util.*;

class GFG {

    // Driver code
    public static void main(String[] args)
    {

        // Creating a list of integers
        List<Integer> list = new ArrayList<Integer>();

        // adding elements in the list
        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);

        // setting the value of N as 4
        int limit = 4;
        int count = 0;
        Iterator<Integer> it = list.iterator();

        // Iterating through the list of integers
        while (it.hasNext()) {
            it.next();
            count++;

            // Check if first four i.e, (equal to N)
            // integers are iterated.
            if (count > limit) {

                // If yes then remove all the remaining integers.
                it.remove();
            }
        }

        System.out.print("New stream of length N"
                         + " after truncation is : ");

        // Displaying new stream of length
        // N after truncation
        for (Integer number : list) {
            System.out.print(number + " ");
        }
    }
}

Output :

New stream of length N after truncation is : -2 0 2 4 

Application :

Java
// Java code to show the use of limit() function
import java.util.stream.Stream;
import java.util.ArrayList;
import java.util.List;
 class gfg{
     
     // Function to limit the stream upto given range, i.e, 3
     public static Stream<String> limiting_func(Stream<String> ss, int range){
         return ss.limit(range);
     }
     
     // Driver code
     public static void main(String[] args){
         
         // list to save stream of strings
         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();
         
         // calling function to limit the stream to range 3
         Stream<String> lm = limiting_func(str,3);
         lm.forEach(System.out::println);
     }
 }

Output :

geeks
for
geeks


Similar Reads

Difference between Stream.of() and Arrays.stream() method in Java
Arrays.stream() The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source. Example: Java Code // Java program to demonstrate Arrays.stream() method import java.uti
5 min read
Character Stream Vs Byte Stream in Java
A stream is a sequence of data. I/O Stream refers to a stream that is unlikely a method to sequentially access a file. I/O Stream means an input source or output destination representing different types of sources e.g. disk files. The java.io package provides classes that allow you to convert between Unicode character streams and byte streams of no
4 min read
foreach() loop vs Stream foreach() vs Parallel Stream foreach()
foreach() loopLambda operator is not used: foreach loop in Java doesn't use any lambda operations and thus operations can be applied on any value outside of the list that we are using for iteration in the foreach loop. The foreach loop is concerned over iterating the collection or array by storing each element of the list on a local variable and do
4 min read
Splitter limit() method | Guava | Java
The method limit(int limit) returns a splitter that behaves equivalently to this splitter but stops splitting after it reaches the limit. The limit defines the maximum number of items returned by the iterator, or the maximum size of the list returned by splitToList(java.lang.CharSequence). For example, Splitter.on(', ').limit(3).split("a, b, c, d")
3 min read
FloatBuffer limit() Method in Java with Examples
The limit() method of java.nio.FloatBuffer Class is used to modify this FloatBuffer's limit. This method takes the limit to be set as the parameter and sets that as the new limit of this Buffer. If the mark of this Buffer is already defined and is larger than the new specified limit, then this new limit is not set and discarded. Syntax: public fina
3 min read
LongBuffer limit() method in Java with Examples
The limit() method of java.nio.LongBuffer Class is used to modify this LongBuffer's limit. This method takes the limit to be set as the parameter and sets that as the new limit of this Buffer. If the mark of this Buffer is already defined and is larger than the new specified limit, then this new limit is not set and discarded. Syntax: public final
3 min read
IntBuffer limit() method in Java with Examples
The limit() method of java.nio.IntBuffer Class is used to modify this IntBuffer's limit. This method takes the limit to be set as the parameter and sets that as the new limit of this Buffer. If the mark of this Buffer is already defined and is larger than the new specified limit, then this new limit is not set and discarded. Syntax: public final In
3 min read
ShortBuffer limit() method in Java with Examples
The limit() method of java.nio.ShortBuffer Class is used to modify this ShortBuffer's limit. This method takes the limit to be set as the parameter and sets that as the new limit of this Buffer. If the mark of this Buffer is already defined and is larger than the new specified limit, then this new limit is not set and discarded. Syntax: public fina
3 min read
Java Stream | Collectors toCollection() in Java
Collectors toCollection(Supplier<C> collectionFactory) method in Java is used to create a Collection using Collector. It returns a Collector that accumulates the input elements into a new Collection, in the order in which they are passed. Syntax: public static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supp
2 min read
ByteBuffer limit() methods in Java with Examples
The limit() method of java.nio.ByteBuffer Class is used to set this buffer's limit. If the position is larger than the new limit then it is set to the new limit. If the mark is defined and larger than the new limit then it is discarded. Syntax: public ByteBuffer limit(int newLimit) Return Value: This method returns this buffer. Below are the exampl
2 min read
Buffer limit() methods in Java with Examples
The limit() method of java.nio.Buffer Class is used to set this buffer's limit. If the position is larger than the new limit then it is set to the new limit. If the mark is defined and larger than the new limit then it is discarded. Syntax: public Buffer limit(int newLimit) Return Value: This method returns this buffer. Below are the examples to il
2 min read
CharBuffer limit() methods in Java with Examples
The limit() method of java.nio.CharBuffer Class is used to set this buffer's limit. If the position is larger than the new limit then it is set to the new limit. If the mark is defined and larger than the new limit then it is discarded. Syntax: public CharBuffer limit(int newLimit) Return Value: This method returns this buffer. Below are the exampl
2 min read
DoubleBuffer limit() methods in Java with Examples
The limit() method of java.nio.DoubleBuffer Class is used to modify this DoubleBuffer's limit. This method takes the limit to be set as the parameter and sets that as the new limit of this Buffer. If the mark of this Buffer is already defined and is larger than the new specified limit, then this new limit is not set and discarded. Syntax: public fi
2 min read
Stream skip() method in Java with examples
Prerequisite : Streams in java The skip(long N) is a method of java.util.stream.Stream object. This method takes one long (N) as an argument and returns a stream after removing first N elements. skip() can be quite expensive on ordered parallel pipelines, if the value of N is large, because skip(N) is constrained to skip the first N elements in the
3 min read
Stream.max() method in Java with Examples
Stream.max() returns the maximum element of the stream based on the provided Comparator. A Comparator is a comparison function, which imposes a total ordering on some collection of objects. max() is a terminal operation which combines stream elements and returns a summary result. So, max() is a special case of reduction. The method returns Optional
3 min read
Stream sorted (Comparator comparator) method in Java
Stream sorted(Comparator comparator) returns a stream consisting of the elements of this stream, sorted according to the provided Comparator. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed. It is a stateful intermediate operation i.e, it may incorporate state from previously seen elements when p
3 min read
Stream min() method in Java with Examples
Stream.min() returns the minimum element of the stream based on the provided Comparator. A Comparator is a comparison function, which imposes a total ordering on some collection of objects. min() is a terminal operation which combines stream elements and returns a summary result. So, min() is a special case of reduction. The method returns Optional
2 min read
Stream generate() method in Java with examples
Stream generate(Supplier<T> s) returns an infinite sequential unordered stream where each element is generated by the provided Supplier. This is suitable for generating constant streams, streams of random elements, etc. Syntax : static <T> Stream<T> generate(Supplier<T> s) Where, Stream is an interface and T is the type of s
1 min read
Stream count() method in Java with examples
long count() returns the count of elements in the stream. This is a special case of a reduction (A reduction operation takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation). This is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect.
2 min read
Stream forEach() method in Java with examples
Stream forEach(Consumer action) performs an action for each element of the stream. Stream forEach(Consumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. Syntax : void forEach(Consumer<? super T> action) Where, Consumer is a functional interface and T is the type of stream elements. Note
2 min read
Stream forEachOrdered() method in Java with examples
Stream forEachOrdered(Consumer action) performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. Stream forEachOrdered(Consumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. Syntax : void forEachOrdered(Consumer<? s
2 min read
Stream noneMatch() Method in Java with Examples
A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. noneMatch() of Stream class returns whether no elements of this stream match the provided predicate. It may not evaluate the predicate on all elements if not necessary for determining the result. This is a short-circuiting terminal
3 min read
Stream.Builder accept() method in Java
Stream.Builder accept(T t) is used to insert an element into the element in the building phase of stream. It adds an element to the stream being built. Syntax: void accept(T t) Parameters: This method accepts a mandatory parameter t which is the element to input into the stream. Exceptions: This method throws IllegalStateException: when the builder
2 min read
Stream.Builder add() method in Java
Stream.Builder add(T t) is used to insert an element into the element in the building phase of stream. It adds an element to the stream being built. Syntax: default Stream.Builder<T> add(T t) Parameters: This method adds a mandatory parameter t which is the element to input into the stream. Exceptions: This method throws IllegalStateException
2 min read
Arrays stream() method in Java
stream(T[] array) The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source. Syntax: public static <T> Stream<T> stream(T[] array) Parameters: This met
3 min read
Stream of() method in Java
Stream of(T t) Stream of(T t) returns a sequential Stream containing a single element. Syntax : static Stream of(T t) Parameters: This method accepts a mandatory parameter t which is the single element in the Stream. Return Value: Stream of(T t) returns a sequential Stream containing the single specified element. Example : // Java code for Stream o
2 min read
BitSet stream() Method in Java with Examples
The stream() method of Java BitSet class is used to return a stream of indices for every bit contained in the BitSet. The indices are returned in increasing order. The size of the stream is the number of bits in the set state of the BitSet, which is equal to the value returned by the cardinality() method. Syntax: public IntStream stream() Parameter
2 min read
Stream iterate(T,Predicate,UnaryOperator) method in Java with examples
The iterate(T, java.util.function.Predicate, java.util.function.UnaryOperator) method allows us to iterate stream elements till the specified condition. This method returns a sequential ordered Stream produced by iterative application of the given next function to an initial element, conditioned on satisfying hasNext predicate passed as parameter.
2 min read
Stream ofNullable(T) method in Java with examples
The ofNullable(T) method returns a sequential Stream containing a single element if this stream is non-null otherwise method returns an empty Stream. It helps to handle the null stream and NullPointerException. Syntax: static <T> Stream<T> ofNullable(T t) Parameters: This method accepts a single parameter t which is the single element o
2 min read
Stream dropWhile() method in Java with examples
The dropWhile(java.util.function.Predicate) method returns two different types of stream depending upon whether the stream is ordered or not. If the stream is ordered then a stream of the remaining elements of this stream after dropping the longest prefix of elements that match the given predicate is returned by method else a stream consisting of t
3 min read