Implementing a custom Spliterator in Java involves creating a class that implements the Spliterator interface. This allows you to define how elements are traversed and partitioned within a data source. Below is an example of implementing a Spliterator for a custom collection of student names.
Implementing Spliterator for Student Names
import java.util.ArrayList;
import java.util.List;
import java.util.Spliterator;
import java.util.function.Consumer;
public class StudentSpliterator implements Spliterator<String> {
private final List<String> students;
private int currentIndex = 0;
public StudentSpliterator(List<String> students) {
this.students = new ArrayList<>(students); // Copying list for immutability
}
@Override
public boolean tryAdvance(Consumer<? super String> action) {
if (currentIndex < students.size()) {
action.accept(students.get(currentIndex++));
return true;
}
return false;
}
@Override
public Spliterator<String> trySplit() {
int currentSize = students.size();
if (currentSize - currentIndex < 2) {
return null; // Not enough elements to split
}
int splitIndex = currentIndex + currentSize / 2;
Spliterator<String> spliterator = new StudentSpliterator(students.subList(currentIndex, splitIndex));
currentIndex = splitIndex;
return spliterator;
}
@Override
public long estimateSize() {
return students.size() - currentIndex;
}
@Override
public int characteristics() {
return ORDERED | SIZED | SUBSIZED | IMMUTABLE;
}
public static void main(String[] args) {
List<String> students = new ArrayList<>();
students.add("Paani");
students.add("Mahesh");
students.add("Datta");
students.add("Ganesh");
students.add("Harsha");
StudentSpliterator spliterator = new StudentSpliterator(students);
// Example of iterating over the spliterator
System.out.println("Iterating over student names:");
spliterator.forEachRemaining(System.out::println);
}
}
/*
Iterating over student names:
Paani
Mahesh
Datta
Ganesh
Harsha
*/
Explanation
- Constructor: The StudentSpliterator constructor initializes with a copy of the list of students to ensure immutability and prevent concurrent modification issues.
- tryAdvance Method: This method attempts to advance the Spliterator by one element. It accepts a Consumer that performs an action on the current element and increments the currentIndex.
- trySplit Method: Splits the elements into two parts for parallel processing. It calculates the split index and creates a new StudentSpliterator instance for the sublist, updating currentIndex
- estimateSize Method: Returns an estimate of the number of elements remaining in the Spliterator.
- characteristics Method: Specifies characteristics of the Spliterator, indicating it is ordered, sized, subsized, and immutable.
- Main Method: Demonstrates usage by creating an instance of StudentSpliterator and iterating over it using forEachRemaining.
