📜  在Java中将迭代器转换为流

📅  最后修改于: 2022-05-13 01:54:56.096000             🧑  作者: Mango

在Java中将迭代器转换为流


给定一个迭代器,任务是将其转换为Java中的 Stream 。

例子:

Input: Iterator = {1, 2, 3, 4, 5}
Output: {1, 2, 3, 4, 5}

Input: Iterator = {'G', 'e', 'e', 'k', 's'}
Output: {'G', 'e', 'e', 'k', 's'}

方法:

  1. 获取迭代器。
  2. 使用 Spliterators.spliteratorUnknownSize() 方法将迭代器转换为 Spliterator。
  3. 使用 StreamSupport.stream() 方法将形成的 Spliterator 转换为 Sequential Stream。
  4. 返回流。

下面是上述方法的实现:

// Java program to get a Stream
// from a given Iterator
  
import java.util.*;
import java.util.stream.*;
  
class GFG {
  
    // Function to get the Stream
    public static  Stream
    getStreamFromIterator(Iterator iterator)
    {
  
        // Convert the iterator to Spliterator
        Spliterator
            spliterator = Spliterators
                              .spliteratorUnknownSize(iterator, 0);
  
        // Get a Sequential Stream from spliterator
        return StreamSupport.stream(spliterator, false);
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Get the Iterator
        Iterator
            iterator = Arrays.asList(1, 2, 3, 4, 5)
                           .iterator();
  
        // Get the Stream from the Iterator
        Stream
            stream = getStreamFromIterator(iterator);
  
        // Print the elements of stream
        stream.forEach(s -> System.out.println(s));
    }
}
输出:
1
2
3
4
5