Java 8 Stream Example: skip() vs limit()

The Java 8 skip() and limit() methods are both intermediate operations that can be used on streams. They both return a new stream that is a subset of the original stream.

The skip() method skips the first n elements of the stream and returns a new stream containing the remaining elements. The limit() method returns a new stream containing the first n elements of the original stream.

Below is an example of how to use skip() and limit():

package the.basic.tech.info;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamExample {

	public static void main(String[] args) {

		List<String> list = Arrays.asList("Java8", "StreamAPI", null, "Test", null);
		List<String> result = list.stream()
				.filter(str -> str != null) //Java8, StreamAPI, Test
				.skip(2) //will Skip Java8 & StreamAPI
				.collect(Collectors.toList());
		result.forEach(System.out::println);
	}

}

Output
Test
package the.basic.tech.info;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamExample {

	public static void main(String[] args) {

		List<String> list = Arrays.asList("Java8", "StreamAPI", null, "Test", null);
		List<String> result = list.stream().filter(str -> str != null) // Java8, StreamAPI, Test
				.skip(2) // will Skip Java8 & StreamAPI
				.limit(0) // limit 0 - no element
				.collect(Collectors.toList());
		result.forEach(System.out::println);
	}

}

Output
<empty>