Java Stream Spliterator

Introduction

Spliterator offers an alternative to Iterator.

It is useful under parallel processing.

tryAdvance() performs an action on the next element and then advances the iterator.

It is shown here:

boolean tryAdvance(Consumer<? super T> action) 

Spliterator makes the iteration loop construct simple:

while(splitItr.tryAdvance( // perform action here ); 

The following version of the preceding program substitutes a Spliterator for the Iterator:

import java.util.ArrayList;
import java.util.Spliterator;
import java.util.stream.Stream; 
 
public class Main { 
 
  public static void main(String[] args) { 
 
    // Create a list of Strings. 
    ArrayList<String> myList = new ArrayList<>(); 
    myList.add("Alpha"); 
    myList.add("Beta"); 
    myList.add("Gamma"); 
    myList.add("Delta"); 
    myList.add("Phi"); 
    myList.add("Omega"); 
 
    // Obtain a Stream to the array list. 
    Stream<String> myStream = myList.stream(); 
 
    // Obtain a Spliterator. 
    Spliterator<String> splitItr = myStream.spliterator(); 
 
    // Iterate the elements of the stream. 
    while(splitItr.tryAdvance((n) -> System.out.println(n))); 
  } // w w  w  .ja v  a2  s.c  o m
}



PreviousNext

Related