GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — Java Spliterator - Complete Tutorial with Examples Java SpliteratorLast modified: May 8, 2025
The
One of the key features of
Understanding these characteristics allows for better optimization of parallel
execution. The metadata provided by the Spliterator Basics
A
Basic Spliterator Usage
This example demonstrates how to use a Main.java
package com.zetcode;
import java.util.List;
import java.util.Spliterator;
public class Main {
public static void main(String[] args) {
List<String> names = List.of("John", "Jane", "Doe", "Sarah");
Spliterator<String> spliterator = names.spliterator();
System.out.println("Characteristics: " + spliterator.characteristics());
System.out.println("Estimated size: " + spliterator.estimateSize());
System.out.println("Elements:");
while (true) {
boolean advanced = spliterator.tryAdvance(name -> System.out.println("Processing: " + name));
if (!advanced) {
break; // Exit loop when all elements are processed
}
}
}
}
The output displays key properties of the
After listing these attributes, the program proceeds to process each element
individually. The
This approach is useful for structured data traversal where elements need to be
processed independently. Additionally, Splitting a Spliterator
A
However, it is important to note that simply calling
In this example, we demonstrate how a Main.java
package com.zetcode;
import java.util.List;
import java.util.Spliterator;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8);
Spliterator<Integer> firstSplit = numbers.spliterator();
Spliterator<Integer> secondSplit = firstSplit.trySplit();
System.out.println("First split:");
firstSplit.forEachRemaining(System.out::println);
System.out.println("Second split:");
secondSplit.forEachRemaining(System.out::println);
}
}
The output illustrates how the original sequence is divided between the two
Enabling Parallel ExecutionTo truly leverage parallel execution, developers need to integrate parallel streams or explicit multi-threading strategies. The easiest way to parallelize processing is using Java's Stream API: List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8);
System.out.println("Processing in parallel:");
numbers.parallelStream().forEach(System.out::println);
The
However, when working with Spliterator, parallel execution does not happen
automatically. The Using Spliterator for Explicit Multi-Threading
For more control over parallel execution, developers can manually create threads
or use an Main.java
package com.zetcode;
import java.util.List;
import java.util.Spliterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8);
Spliterator<Integer> firstSplit = numbers.spliterator();
Spliterator<Integer> secondSplit = firstSplit.trySplit();
// Using an ExecutorService to process splits in parallel
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
executor.submit(() -> {
System.out.println("First split processing by " + Thread.currentThread().getName());
firstSplit.forEachRemaining(num -> System.out.println(Thread.currentThread().getName() + " - " + num));
});
executor.submit(() -> {
System.out.println("Second split processing by " + Thread.currentThread().getName());
secondSplit.forEachRemaining(num -> System.out.println(Thread.currentThread().getName() + " - " + num));
});
executor.shutdown();
}
}
}
This implementation correctly enables parallel execution using
Choosing the Right ApproachParallel streams are the simplest way to execute operations concurrently, making them ideal for general-purpose collection processing. On the other hand, manual threading with Spliterator provides finer control, allowing developers to explicitly distribute workloads across multiple threads.
Understanding the distinction between splitting a Characteristics of SpliteratorThis example demonstrates how to examine the characteristics of a Spliterator. Characteristics provide metadata about the data source that can be used to optimize processing. We create Spliterators from different sources and examine their characteristics. Main.java
package com.zetcode;
import java.util.HashSet;
import java.util.List;
import java.util.Spliterator;
import java.util.TreeSet;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
printCharacteristics("List", List.of(1, 2, 3).spliterator());
printCharacteristics("Set", new HashSet<>(List.of(1, 2, 3)).spliterator());
printCharacteristics("SortedSet", new TreeSet<>(List.of(1, 2, 3)).spliterator());
printCharacteristics("Stream", Stream.of(1, 2, 3).spliterator());
}
private static void printCharacteristics(String source, Spliterator<Integer> spliterator) {
System.out.println(source + " characteristics:");
System.out.println("ORDERED: " + spliterator.hasCharacteristics(Spliterator.ORDERED));
System.out.println("DISTINCT: " + spliterator.hasCharacteristics(Spliterator.DISTINCT));
System.out.println("SORTED: " + spliterator.hasCharacteristics(Spliterator.SORTED));
System.out.println("SIZED: " + spliterator.hasCharacteristics(Spliterator.SIZED));
System.out.println("NONNULL: " + spliterator.hasCharacteristics(Spliterator.NONNULL));
System.out.println("IMMUTABLE: " + spliterator.hasCharacteristics(Spliterator.IMMUTABLE));
System.out.println("CONCURRENT: " + spliterator.hasCharacteristics(Spliterator.CONCURRENT));
System.out.println("SUBSIZED: " + spliterator.hasCharacteristics(Spliterator.SUBSIZED));
System.out.println();
}
}
The output shows how different collection types have different characteristics. For example, a List is ORDERED and SIZED, a Set is DISTINCT, and a SortedSet is also SORTED. These characteristics help the Stream API optimize its operations. Creating a Custom Spliterator
This example demonstrates how to create a custom
In this implementation, a specialized Main.java
import java.util.Spliterator;
import java.util.function.Consumer;
public class Main {
static class EvenNumberSpliterator implements Spliterator<Integer> {
private int current = 0;
private final int max;
public EvenNumberSpliterator(int max) {
this.max = max;
}
@Override
public boolean tryAdvance(Consumer<? super Integer> action) {
if (current <= max) {
action.accept(current);
current += 2;
return true;
}
return false;
}
@Override
public Spliterator<Integer> trySplit() {
int mid = (max - current) / 2;
if (mid <= 1) return null;
int newCurrent = current + mid + (mid % 2);
EvenNumberSpliterator newSplit = new EvenNumberSpliterator(newCurrent - 2);
current = newCurrent;
return newSplit;
}
@Override
public long estimateSize() {
return (max - current) / 2 + 1;
}
@Override
public int characteristics() {
return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.NONNULL;
}
}
public static void main(String[] args) {
Spliterator<Integer> spliterator = new EvenNumberSpliterator(20);
System.out.println("Even numbers:");
boolean hasMoreElements;
do {
hasMoreElements = spliterator.tryAdvance(System.out::println);
} while (hasMoreElements);
// Parallel processing demonstration
Spliterator<Integer> parallelSplit = new EvenNumberSpliterator(20);
Spliterator<Integer> split1 = parallelSplit.trySplit();
System.out.println("First half:");
split1.forEachRemaining(System.out::println);
System.out.println("Second half:");
parallelSplit.forEachRemaining(System.out::println);
}
}
This custom
A key feature of this
Using Spliterator with StreamsThis example shows how Spliterator is used internally by the Stream API. We'll create a stream from a Spliterator and demonstrate both sequential and parallel processing. This shows the real power of Spliterator in enabling parallel stream operations. Main.java
package com.zetcode;
import java.util.List;
import java.util.Spliterator;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public class Main {
public static void main(String[] args) {
List<String> words = List.of("apple", "banana", "cherry",
"date", "elderberry");
// Create stream from Spliterator
Spliterator<String> spliterator = words.spliterator();
Stream<String> stream = StreamSupport.stream(spliterator, false);
System.out.println("Sequential processing:");
stream.forEach(System.out::println);
// Parallel processing
Spliterator<String> parallelSplit = words.spliterator();
Stream<String> parallelStream = StreamSupport.stream(parallelSplit, true);
System.out.println("Parallel processing:");
parallelStream.forEach(System.out::println);
}
}
The example demonstrates how Spliterators enable both sequential and parallel
stream processing. The second parameter to Spliterator for Primitive Types
Java provides specialized Spliterators for primitive types:
Main.java
package com.zetcode;
import java.util.Arrays;
import java.util.Spliterator;
import java.util.stream.IntStream;
import java.util.stream.StreamSupport;
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8};
Spliterator.OfInt intSpliterator = Arrays.spliterator(numbers);
System.out.println("Characteristics: " + intSpliterator.characteristics());
System.out.println("Estimated size: " + intSpliterator.estimateSize());
// Process elements
System.out.println("Elements:");
intSpliterator.forEachRemaining((int value) ->
System.out.println("Value: " + value));
// Create IntStream from Spliterator
Spliterator.OfInt streamSpliterator = Arrays.spliterator(numbers);
IntStream intStream = StreamSupport.intStream(streamSpliterator, true);
System.out.println("Sum: " + intStream.sum());
}
}
This example shows the specialized OfInt SourceJava Spliterator Documentation
In this article, we've covered the essential aspects of the Java
AuthorMy name is Jan Bodnar, and I am a dedicated programmer with many years of experience in the field. I began writing programming articles in 2007 and have since authored over 1,400 articles and eight e-books. With more than eight years of teaching experience, I am committed to sharing my knowledge and helping others master programming concepts. List all Java tutorials. |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |