×

Spliterator in Java 8

In this tutorial, we will understand the meaning of spliterator in java 8. It is just like any other iterator available in java used to traverse the elements of either collection or generator function. It is of great importance in java. It offers some methods to use parallel programming features. However, it directly supports the sequential processing of data. It is an interface present in the Java collection.

There are following eight methods offered by the spliterator interface.

  1. Characteristics()
  2. estimateSize()
  3. getExactSizeIfKnown()
  4. hasCharacteristics()
  5. getComparator()
  6. tryAdvance(Consumer action)
  7. trySplit()
  8. forEachRemaining(Consumer action)

Now, let us understand each of the above methods one by one.

Characteristics():

Syntax - int characteristics()

This method does not accept any argument and returns the nature and elements of the calling spliterator.

estimateSize():

Syntax –estimateSize()

This method is to get the estimate of the count of elements remaining for iteration. This method does not accept any argument and returns the count of elements.

getExactSizeIfKnown():

Syntax – default long getExactSizeIfKnown()

This method also does not accept any parameter and returns the count ofelements that are remained to be iterated.

hasCharacteristics():

Syntax –default booleanhasCharacteristics(int characteristics)

This method is takeninto account to detect if the characteristics of the spliterator include all the given characteristics or not.

This method takes the parameter as input and returns true if the characteristics are existing in the spliterator and false if it is not present there.

getComparator():

Syntax - booleantryAdvance()

This method is taken into account to sort. It does not accept any argument but returns some values.

  • The method gives out null in the case when the source is sorted in the usualdirection.
  • When the source is unsorted, then this method throws an exception called IllegalStateException.

tryadvance():

Syntax - boolean tryAdvance(Consumer<?super T> action)

It accepts action as an argument and returns This method is taken into account toexecute the given action on the remaining elements and returns true. it returns false if the elements are absent.

trysplit():

Syntax - Spliterator trySplit()

This method does not accept any parameter and returns a spliterator that covers nearly some percentage of the elements or is null if the spliterator can’t get split.

forEachRemaining():

Syntax - default void forEachRemaining(Consumer action)

This method is taken into account to execute the specified is used to perform an action on each portion consecutively. It executesan action when the processing of each element is completed or unless the action throws NullPointerException.

Implementation:

Let us try to understand the spliterator methods in a java program.

// packages required for classes
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Spliterator;
import java.util.stream.Stream;


// class named SpliteratorEg1 is created to comprehend all the methods of the Spliterator class
public class SpliteratorEg1 {
// main() method
public static void main(String[] args) {
int size;


// creation of a Scanner class object to get inputs from the user
Scanner sc = new Scanner(System.in);


// Creation of an array list.
ArrayList<Integer>age_list;


System.out.println("Enter the size of the ArrayList:");
size = sc.nextInt();


age_list = new ArrayList<Integer>(size);


for(int i = 0; i< size; i++) {
System.out.println("Enter "+(i+1)+" Age:");
int value = sc.nextInt();
age_list.add(value);
}


// closing the Scanner class object
sc.close();


//   getting a Stream to the array list by using the stream() method.
Stream<Integer> stream1 = age_list.stream();


//  getting the Spliterator object on ages by using the spliterator() method
Spliterator<Integer> spliterator1 = stream1.spliterator();


//  getting the estimate size by using estimateSize()method
System.out.println("The estimated size of the ArrayListis : " + spliterator1.estimateSize());


// getting  the exact size of ArrayList if known by using getExactSizeIfKnown() method
System.out.println("The exact size of the ArrayList is: " + spliterator1.getExactSizeIfKnown());


// using hasCharacteristics() and characteristics() methods
System.out.println(spliterator1.hasCharacteristics(spliterator1.characteristics()));


System.out.println("Elements of the ArrayList:");


// using forEachRemaining() method to display each element of the ArrayList
spliterator1.forEachRemaining((n) ->System.out.println(n));


// using the stream() to get another Stream to the ArrayList.
Stream<Integer> stream2 = age_list.stream();
spliterator1 = stream2.spliterator();


// using trySplit() method
Spliterator<Integer> spliterator2 = spliterator1.trySplit();


// Use spliterator2 first in the case spliterator1 could be split,
if(spliterator2 != null) {
System.out.println("Elements of the ArrayList obtained through spliterator2: ");
spliterator2.forEachRemaining((n) ->System.out.println(n));
}


// Now, using the spliterator1
System.out.println("\nElements of the ArrayList obtained from spliterator1");
spliterator1.forEachRemaining((n) ->System.out.println(n));


}
}

Output:

Spliterator in Java 8
Spliterator in Java 8

Explanation: In this code, the user is asked to enter the size of the array and the values. Those values are displayed using different spliterator methods.


Related Topics

CopyOnWriteArrayList in Java

The CopyOnWriteArrayList is used to implement the List Interface. It is the improved version of ArrayList. The operations like add, remove, set, update etc, these operations are done by creating...

5 minutes read.

ArrayList VS Linked List

ArrayList VS Linked List Both the ArrayList and LinkedList implements the List interface, and they have some differences as well as some similarities between them. The internal working and performance of both vary significantly. Let’s...

7 minutes read.

Java Integer toOctalString() method

The toOctalString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 8. Syntax public static String toOctalString (int  i) Parameters The parameter ‘i’ represents...

1 minute read.

Quick Sort in Java

Quick Sort in Java Like merge sort, quick sort also uses the divide and conquer approach to sort the given array or list. In quick sort, the sorting of an array...

6 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

Java StringBuffer vs StringBuilder

Java StringBuffer vs StringBuilder StringBuffer The StringBuffer class is used to create mutable string. StringBuffer shows writable and growable character sequences. Java StringBuffer program FileName: StringBufferExample.java // A basic program that demonstrates the working...

2 minutes read.

Java vs Golang

Java Java is both a programming language and a platform. Java is a high-level, dependable, object-oriented, and secure programming language. Java was developed in 1995 by Sun Microsystems, which is now an...

4 minutes read.

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.

Java time local date

Java: Java is one of the programming language which is object oriented. It consists of many features such as robust, simple, architecture neutral, dynamic, distributed, multi threaded, portable etc. The main feature...

3 minutes read.

How to Run Applet Program in Java

An applet is a new type of program which is put in a webpage. By inserting applet into a webpage dynamic content can be created. Characteristics of an Applet The applet is...

11 minutes read.

Java Queue

The Java.util package has the interface Queue, which does extend the Collection interface. It is used to protect the parts that are managed using the FIFO approach. Being an interface, the...

5 minutes read.

Java Integer highestOneBit()

The highestOneBit() method of Java Integer class returns an int value with at most a single one-bit, in the position of the highest-order one-bit in the specified int value.  Syntax public static...

1 minute read.

How to Read CSV Files in Java?

Comma-Separated Values is the acronym for this format. It is a straightforward file format storing textual tabular data in a database or spreadsheet. The CSV files can be imported into...

3 minutes read.

Java Pi

What is Pi? There are many formulas in geometry that employ the Pi constant to calculate things like circumference, area, and volume. A circle's circumference divided by its diameter yields a...

3 minutes read.

Accessors and Mutator in Java

Introduction Accessors and mutators are used in Java to get and set the value of private fields, respectively. Accessors and mutators are both referred to as getters and setters, respectively. The...

6 minutes read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same...

4 minutes read.

Zig Zag star and Number Pattern in Java

We covered many Java pattern applications in the preceding part. We will write Java applications for zigzag star and number patterns in this part. Printing Zig Zag Number Pattern Steps Print one...

3 minutes read.

Java Obfuscator

Obfuscation is the process of making something unclear or difficult to interpret. Obfuscators are being used in programming to protect the source code from hackers. In this article, we will...

8 minutes read.

How to Reverse a String in Java

How to Reverse a String in Java There are a lot of ways to reverse a string in Java. One can use iteration, StringBuilder, StringBuffer to do the reverse of a...

6 minutes read.