×

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

Empty Statement in Java

The three sorts of statements in Java are control, expression, and declaration statements. Additionally, another statement is referred to as an empty statement. In this section, we will discuss about...

4 minutes read.

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements....

4 minutes read.

Java Worker Class

What is a Worker? A service which executes Work - flow and Activities is referred to as a Worker. On user-controlled hosts, workers are defined and put into action. The Worker...

3 minutes read.

Cyclic Barrier in Java

Programmers often find it challenging to run multiple threads simultaneously. Java introduces the idea of concurrency, which enables us to run many threads concurrently, making this work simpler. Concurrent programming...

6 minutes read.

Big Decimal class in Java

The fairly Big pretty Decimal class provides operations for arithmetic, rounding, comparison and format conversion in a sort of big way. It can handle generally large and very small floating-point...

6 minutes read.

How to uninstall the Java in Ubuntu

We need java on our computers in our daily lives because there are lots of different applications that are developed using the java environment, so we have to install java...

4 minutes read.

Java Calculate Average of List

The list is a linear data structure used in Java to store ordered data collections. Additionally, it accepts duplicate values while maintaining insertion order. It is sometimes necessary to find...

3 minutes read.

Finding middle node of a linked list in Java

To find the middle node of a linked list we have various methods in Java. Method 1 In this method two pointers are used, one of which advances quickly, and the other of...

6 minutes read.

PriorityQueue in Java

PriorityQueue in Java A PriorityQueue is a member of the Java Collection Framework and is used when the values are needed to be processed based on priority. Priority queue operates similar to...

8 minutes read.

Java Integer numberOfLeadingZeros() method

The numberOfLeadingZeros()  method of Java Integer class returns the total number of zero bits preceding the highest-order one-bit in the 2’s complement binary representation of the specified int value.  Syntax public static...

1 minute read.

HttpURLConnection

HttpURLConnection Protocol It is a standard set of rules that allow electronic devices to communicate with each other. The http protocol The http protocol is for data communication, distributing, collaborating, hypermedia information systems, on the World Wide...

5 minutes read.

Java Math nextAfter() Method

The nextAfter() method of Math class returns the floating-point value adjacent to the first argument in direction of the second argument. Syntax: public static double nextAfter (double start, double direction)public static float...

2 minutes read.

Java Wrapper classes

Java Wrapper classes A wrapper class is a class whose object contains a primitive data type; moreover it provides a way to use primitive data type (int, boolean, etc.) as objects. Wrapper...

2 minutes read.

Kong Java Client

Kong is an Organization Microservice Programming interface gateway. Kong gives an adaptable deliberation layer that safely oversees correspondence among clients and microservices by means of a Programming interface. Otherwise called...

6 minutes read.

Java Imageio

The javax.imageio package contains the final class known as Java ImageIO. For easy image reading, writing, and simple encoding and decoding, the class offers a convenient way. The class offers...

4 minutes read.

How to remove last character from String in Java

In java, there are predominantly three classes connected with the string. The classes are String, StringBuilder, and StringBuffer class that gives techniques connected with string control. Eliminating the first and...

5 minutes read.

Java LinkedList vs ArrayList

LinkedList In LinkedList, each element is a distinct entity containing an information portion and an address component, and the elements are not kept in consecutive locations. Pointers & addresses are used...

3 minutes read.

Hybrid Inheritance in Java

The most crucial OOPs concept in Java is inheritance, which enables the transfer of a class's properties to another class. It describes the Is-A relationship generally. We can create a...

3 minutes read.

Repdigit Numbers in Java

A combination of repeated and digit, the term is. A repdigit, also known as a monodigit or a positional number system, is a natural number in recreational mathematics made up...

3 minutes read.

Two Decimal Places Java

When a double data type is used in Java before a variable, this indicates 15 digits after decimal point. However, there are situations when we only require 2 decimal places...

4 minutes read.