skip() example



Example:
import java.util.Arrays;
import java.util.List;

public class SkipFlight {
    public static void main(String[] args) {
        System.out.println("main() [Start]");


       List<Integer> numbers = Arrays.asList(6,10, 20, 10, 3, 2, 4, 6, 9);

       
        numbers
        .stream()
        .filter(num->num%2==0)
        .skip(2)

        .forEach(System.out::println);

       
        System.out.println("main() [End]");
    }
}


Ouput:
main() [Start]
20
10
2
4
6
main() [End]


Explanation:

 .filter(num->num%2==0) :
  • filter takes the lamda expression as an argument. 
  • It takes a lamda expression having functional interface having abstract method which take one argument and return boolean result. 
  • It returns the Stream of given type parameter. 
    .skip(2):
  • this method works on the stream returned from the filter method
  • It returns the Stream by skipping the first n elements.
  • If total number of elements in stream are less than n then it will return empty stream
  • The limit(n) method and skip(n) method are complementary!
     .forEach(System.out::println):
  • This method works on the stream returned from the skip method
  • This is a terminal operation method because it doesnt return the stream.
  • All the previous streams maintained as pipeline and processed when this method get called
  • This method takes a consumer functional interface lamda expression or method reference as argument and it consumes the data of previous streams. Here it consumes and display each element.