x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    Java 8 Spliterator example

    A Spliterator object is used to traverse a collection or stream and it can split the stream source for parallel processing.

    1) Spliterator trySplit() example

    package java8;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Spliterator;
    
    public class SpliteratorExample {
        public static void main(String[] args) {
        	 
            List<String> list = Arrays.asList("Mark", "John", "Andrew");
    
        	Spliterator<String> s2 = list.spliterator();
        	Spliterator<String> s1 = s2.trySplit();
            
            System.out.println("Iterating using first iterator");
        	s2.forEachRemaining(System.out::println);
            System.out.println("Iterating using second iterator");
        	s1.forEachRemaining(System.out::println);
        }
    }
    	
    	

    Console Output :

    Iterating using first iterator
    John
    Andrew
    Iterating using second iterator
    Mark
    	

    2) Spliterator tryAdvance() example

    package java8;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Spliterator;
    
    public class SpliteratorExample {
        public static void main(String[] args) {
        	 
            List<String> list = Arrays.asList("Mark", "John", "Andrew");
    
            Spliterator<String> s = list.spliterator();
            s.tryAdvance(System.out::println);
            s.tryAdvance(System.out::println);
            boolean b = s.tryAdvance(System.out::println);
            System.out.println("Element exists: " + b);
    
            b = s.tryAdvance(System.out::println);
            System.out.println("Element exists: " + b);
        }
    }
    	
    	

    Console Output :

    Mark
    John
    Andrew
    Element exists: true
    Element exists: false
    	

    3) Spliterator forEachRemaining() example

    package java8;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Spliterator;
    
    public class SpliteratorExample {
        public static void main(String[] args) {
        	 
            List<String> list = Arrays.asList("Mark", "John", "Andrew");
            Spliterator<String> s = list.spliterator();
            System.out.println("Processing using forEachRemaining");
            s.forEachRemaining(System.out::println);
        }
    }
    	
    	

    Console Output :

    Processing using forEachRemaining
    Mark
    John
    Andrew
    	



    References :

    Oracle Docs Spliterator

    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *











    Share This