Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
stream.limit() method in Java
Next article icon

stream.limit() method in Java

Last Updated : 27 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 

Next Article
stream.limit() method in Java

S

Sahil_Bansall
Improve
Article Tags :
  • Misc
  • Java
  • Java - util package
  • Java-Functions
  • java-stream
  • Java-Stream interface
Practice Tags :
  • Java
  • Misc

Similar Reads

    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 spec
    2 min read
    Arrays.stream() Method in Java
    Arrays.stream() method is used to get a sequential Stream from the elements of an array passed as a parameter. Below is a simple example that uses Arrays.stream() to convert a String array into a Stream for sequential processing.Example:Java// Java program to demonstrate Arrays.stream() method impor
    3 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 examp
    3 min read
    Stream sorted() in Java
    Stream sorted() returns a stream consisting of the elements of this stream, sorted according to natural order. 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 s
    2 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 spec
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences