Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

spliterator()

Example

Employ a Spliterator to iterate through elements in a list.

import java.util.LinkedList;
import java.util.Spliterator;

public class Main {
  public static void main(String[] args) {
  
    // Make a collection
    LinkedList<String> cars = new LinkedList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");
  
    // Get the spliterator and split it
    Spliterator<String> it1 = cars.spliterator();
    Spliterator<String> it2 = it1.trySplit();
    
    // Loop through the first spliterator
    System.out.println("First spliterator");
    while( it1.tryAdvance( (n) -> { System.out.println(n); } ) );
    
    // Loop through the second spliterator
    System.out.println("\nSecond spliterator");
    while( it2.tryAdvance( (n) -> { System.out.println(n); } ) );
  }
}

Note: The syntax while( it1.tryAdvance( (n) -> { System.out.println(n); } ) ); is similar to:

boolean x = it1.tryAdvance( (n) -> { System.out.println(n); });
while(x) {
  x = it1.tryAdvance( (n) -> { System.out.println(n); });
}

Definition and Usage

The spliterator() method provides a Spliterator for the list. The Spliterator differs significantly from a standard iterator. It aims to divide a collection into smaller segments so that each segment can be processed by a separate thread.

The Spliterator interface includes two crucial methods:

trySplit() – Produces a new spliterator capable of traversing (usually, roughly half of) the elements accessible to the original spliterator, while the original can traverse the remaining portion.

tryAdvance(Consumer action) – Progresses to the next available item for the spliterator and attempts to execute an action on it. If there is no next item, it returns false. The action can be specified using a lambda expression.

 


Syntax

public Spliterator spliterator()

Technical Details

Returns:

Spliterator object.

Java version:

1.8+