1.

What is Spliterator in Java SE 8?

Answer»

Spliterator is used for traversing the elements of a Collection, GENERATOR function, IO channel etc. It provides excellent support for parallel traversal as well as sequential traversal and hence is INCLUDED in the JDK 8.

The Spliterator is quite useful EVEN if parallel traversal is not REQUIRED as it combines the hasNext and next operations into a single method.

A program that demonstrates a Spliterator in Java is given as follows:

import java.util.ArrayList; import java.util.Spliterator; import java.util.stream.Stream; public class SpliteratorDemo   {    public static void main(String[] args)      {        ArrayList<Integer> arrList = new ArrayList<>();        arrList.add(7);        arrList.add(2);        arrList.add(1);        arrList.add(9);        arrList.add(4);        Stream<Integer> s1 = arrList.stream();        Spliterator<Integer> split = s1.spliterator();        System.out.println("The estimated size is: " + split.estimateSize());        System.out.println("The arraylist contents are:");        split.forEachRemaining((n) -> System.out.println(n));    } }

The output of the above program is as follows:

The estimated size is: 5 The arraylist contents are: 7 2 1 9 4


Discussion

No Comment Found