$show=/label

Java 8 Stream limit() Method Example

SHARE:

Learn and understand the java 8 stream api limit() method to limit and reduce the stream size given to the limit method for the given max size.

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?

Java 8 Stream limit() Method Example


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));

	}

}
Output:
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);

	}

}

Output:
Original list before : [one, two, four, five, six]
limiting to 2 after sorting : [two, six]

7. Stream limit() Example 4 before Java 8


Let us create the limit functionality before java 8 and how it can be achieved using List, iterator() and remove() methods.
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);
		

	}

}
Output:
Original list before limit logic [java 8, programs, on, javaprogram.com, new, blog]
After limiting to 5 strings : [java 8, programs, on]

8. Conclusion


In this article, you've seen how to reduce the size of the list or stream in java 8 using stream limit() method.

As usual, all examples are shown are over GitHub.



COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,16,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,23,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,84,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,12,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,10,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,30,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,77,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,93,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Matrix,5,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,23,String,58,String Programs,12,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 Stream limit() Method Example
Java 8 Stream limit() Method Example
Learn and understand the java 8 stream api limit() method to limit and reduce the stream size given to the limit method for the given max size.
https://1.bp.blogspot.com/-EGuzdoYaKZE/Xzq6ugYsS4I/AAAAAAAAC64/uO_lYW7pqfoekER06SJJfas3ok5e-d-2ACLcBGAsYHQ/w640-h358/Java%2B8%2BStream%2Blimit%2528%2529%2BMethod%2BExample.png
https://1.bp.blogspot.com/-EGuzdoYaKZE/Xzq6ugYsS4I/AAAAAAAAC64/uO_lYW7pqfoekER06SJJfas3ok5e-d-2ACLcBGAsYHQ/s72-w640-c-h358/Java%2B8%2BStream%2Blimit%2528%2529%2BMethod%2BExample.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/08/java-8-stream-limit-method-example.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/08/java-8-stream-limit-method-example.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content