In Java Stream API skip(long n) method is used to skip the first 'n' elements of the stream and return a stream consisting of the remaining elements of this stream.
Java Stream skip() method
Syntax of the skip method is as given below-
Stream<T> skip(long n)
Here n represents the number of leading elements to skip.
Method returns a new stream consisting of the remaining elements of this stream after skip operation. Since a new stream is returned that means skip() is a stateful intermediate operation.
If n is passed as a negative number, then IllegalArgumentException is thrown.
If this stream contains fewer than n elements then an empty stream will be returned.
skip() Java examples
1. To get a sublist from a List using skip method.
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class StreamSkip { public static void main(String[] args) { StreamSkip ss = new StreamSkip(); // Get sublist from the list of Integers List<Integer> numList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); List<Integer> subList = ss.getSubList(numList, 4); System.out.println("Sublist after skipping elements- " + subList); // Get sublist from the list of Strings List<String> strList = Arrays.asList("one", "two", "three", "four", "five","six","seven","eight","nine","ten"); List<String> strSubList = ss.getSubList(strList, 5); System.out.println("Sublist after skipping elements- " + strSubList); } public <T> List<T> getSubList(List<T> firstList, long n){ return firstList.stream().skip(n).collect(Collectors.toList()); } }
Output
Sublist after skipping elements- [5, 6, 7, 8, 9, 10] Sublist after skipping elements- [six, seven, eight, nine, ten]
2. If n is greater than the stream size
public class StreamSkip { public static void main(String[] args) { StreamSkip ss = new StreamSkip(); List<Integer> numList = Arrays.asList(1, 2, 3, 4, 5, 6); List<Integer> subList = numList.stream().skip(7).collect(Collectors.toList()); System.out.println("Sublist after skipping elements- " + subList); } }
Output
Sublist after skipping elements- []
As you can see an empty stream is returned because elements you are trying to skip is more than the size of the stream itself.
That's all for this topic Java Stream - skip() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Advanced Tutorial Page
Related Topics
You may also like-
No comments:
Post a Comment