"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Convert an Iterator to a Stream Without Creating a Copy?

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

Published on 2024-11-22
Browse:490

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:

Iterator sourceIterator = Arrays.asList("A", "B", "C").iterator();
Stream targetStream = StreamSupport.stream(
          Spliterators.spliteratorUnknownSize(sourceIterator, Spliterator.ORDERED),
          false);

Method 2: Using Iterable

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

Iterator sourceIterator = Arrays.asList("A", "B", "C").iterator();

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

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3