Home  >  Article  >  Java  >  How to Convert an Iterator to a Stream Without Creating a Copy?

How to Convert an Iterator to a Stream Without Creating a Copy?

Barbara Streisand
Barbara StreisandOriginal
2024-11-07 01:05:02992browse

How to Convert an Iterator to a Stream Without Creating a Copy?

Converting Iterator to Stream Without Copying

Converting an Iterator directly to a Stream without creating an intermediate copy is a desirable operation for performance reasons. Here are two effective methods to achieve this conversion:

Method 1: Using Spliterator

Create a Spliterator from the Iterator using the Spliterators class and use it as the basis for the Stream:

<code class="java">Iterator<String> sourceIterator = Arrays.asList("A", "B", "C").iterator();
Stream<String> targetStream = StreamSupport.stream(
          Spliterators.spliteratorUnknownSize(sourceIterator, Spliterator.ORDERED),
          false);</code>

Method 2: Using Iterable

Create an Iterable from the Iterator using a lambda expression. Iterable is a functional interface, which makes this conversion straightforward:

<code class="java">Iterator<String> sourceIterator = Arrays.asList("A", "B", "C").iterator();

Iterable<String> iterable = () -> sourceIterator;
Stream<String> targetStream = StreamSupport.stream(iterable.spliterator(), false);</code>

The key to avoiding a copy in both methods is that they utilize the StreamSupport class, which allows you to create a Stream directly from a Spliterator or Iterable without intermediate collection manipulation.

The above is the detailed content of How to Convert an Iterator to a Stream Without Creating a Copy?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn