CloseableIterableStream<T> Class

Type Parameters

T

The type of values in this stream.

Implements

public final class CloseableIterableStream<T>
extends IterableStream<T>
implements Closeable

An IterableStream<T> that provides deterministic cleanup for resource-backed iteration.

This stream takes ownership of the resource associated with the supplied iterable. After construction, manage the resource's lifetime through this stream rather than closing the resource directly.

Iteration behavior, including whether multiple iterators are supported, is determined by the supplied iterable. Use this stream in a try-with-resources statement to ensure that the owned resource is released whether iteration completes normally or ends early. Closing the stream is safe to do more than once.

Code sample

BufferedReader reader = getReader();
 Iterable<String> lines = () -> reader.lines().iterator();

 try (CloseableIterableStream<String> stream = new CloseableIterableStream<>(lines, reader)) {
     for (String line : stream) {
         System.out.println(line);
     }
 } catch (IOException exception) {
     throw new UncheckedIOException("Failed to close the reader.", exception);
 }

Constructor Summary

Constructor Description
CloseableIterableStream(Iterable<T> iterable, Closeable ownedResource)

Creates an iterable stream that owns the resource associated with its iteration.

Method Summary

Modifier and Type Method and Description
void close()

Releases the resource owned by this stream.

Stream<T> stream()

Gets a Java stream of values that closes this iterable stream when the returned stream is closed.

Methods inherited from IterableStream

Methods inherited from java.lang.Object

Constructor Details

CloseableIterableStream

public CloseableIterableStream(Iterable<T> iterable, Closeable ownedResource)

Creates an iterable stream that owns the resource associated with its iteration.

Parameters:

iterable - The iterable that reads values from, or is otherwise associated with, the owned resource.
ownedResource - The resource whose ownership is transferred to this stream and which is released when this stream is closed.

Method Details

close

public void close()

Releases the resource owned by this stream.

This method is idempotent.

Throws:

IOException

- If the owned resource fails to close.

stream

public Stream<T> stream()

Gets a Java stream of values that closes this iterable stream when the returned stream is closed.

Closing the returned Java stream also closes this iterable stream. If this iterable stream isn't managed with try-with-resources, the returned Java stream must be explicitly closed to release the owned resource. Terminal operations don't automatically close it.

Overrides:

CloseableIterableStream<T>.stream()

Returns:

A Java stream of values.

Applies to