Java 把迭代器转换为流
给定一个Iterator,任务是在Java中把它转换成Stream。
例子。
输入: Iterator = {1, 2, 3, 4, 5}
输出: {1, 2, 3, 4, 5}
输入: Iterator = {‘G’, ‘e’, ‘e’, ‘k’, ‘s’}
输出: {‘G’, ‘e’, ‘e’, ‘k’, ‘s’}
办法。
- 获取迭代器。
- 使用Spliterators.spliteratorUnknownSize()方法将迭代器转换为Spliterator。
- 使用StreamSupport.stream()方法将形成的Spliterator转换成顺序流。
- 返回流。
下面是上述方法的实现。
// 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 <T> Stream<T>
getStreamFromIterator(Iterator<T> iterator)
{
// Convert the iterator to Spliterator
Spliterator<T>
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<Integer>
iterator = Arrays.asList(1, 2, 3, 4, 5)
.iterator();
// Get the Stream from the Iterator
Stream<Integer>
stream = getStreamFromIterator(iterator);
// Print the elements of stream
stream.forEach(s -> System.out.println(s));
}
}
输出:
1
2
3
4
5