How to Skip Elements with the Skip Method in Java 8
See Java: Tips and Tricks for similar articles.
If you need to bypass a certain number of elements in a collection, you can apply the skip method to a stream produced from the collection in Java 8. The following four steps show how to skip elements using the skip method.
- Open your text editor and create the Java program that will create the stream and apply the skip method. Type in the following Java statements:
The stream will be created from the ArrayList that is defined on line 4. Note that a static block is used to add elements to the ArrayList. A static block is executed one time when the program is loaded into memory. The program will display the original list and then skip over the first four elements and display the remaining elements. I have highlighted the skip method in the image below:
import java.util.stream.*; import java.util.*; public class SkipElements { private static Listnames=new ArrayList<>(); static { names.add("Stephen"); names.add("Regina"); names.add("Edward"); names.add("Miguel"); names.add("George"); names.add("Brad"); names.add("Jose"); } public static void main (String args[]) { System.out.println("Collection without skipping elements: "); names.stream().forEach(System.out::println); System.out.println("Collection after skipping 4 elements: "); names.stream().skip(4).forEach(System.out::println); } } 
- Save your file as
SkipElements.java. - Open a command prompt and navigate to the directory containing your new Java program. Then type in the command to compile the source and hit Enter.

- You are ready to test your Java program. Type in the command to run the Java runtime launcher and hit Enter. The output displays the collection before and after skipping over the first four elements.

