How to Skip Elements with the Skip Method in Java 8

  • google plus

In Brief...

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.

Take our Introduction to Java Training course for free.

See the Course Outline and Register

Instructions

  1. 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:
    
    import java.util.stream.*;
    import java.util.*;
    public class SkipElements {
    	private static List names=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);
    	}
    }
    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:
    Java Source for Skip Method
  2. Save your file as SkipElements.java.
  3. 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.
    Compile Program with Skip Method
  4. 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.
    Run Program with Skip Method

Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

Discuss