Java 8中如何将Iterator转换为Stream呢?
下文笔者讲述jdk8中将Iterator转换为Stream的方法分享,如下所示
所以需要使用Spliterators.spliteratorUnknownSize将Iterator转换为Spliterator
再使用StreamSupport.stream将Spliterator转换为Stream
所以非常方便就可以将其转换为Stream
Iterator转Stream的实现思路
使用StreamSupport.stream方法即可 将Iterator转换为Stream 例: // Iterator -> spliterators -> Stream Stream<String> stream = StreamSupport.stream( Spliterators.spliteratorUnknownSize( iterator, Spliterator.ORDERED) , false);ator 。
StreamSupport源码
public static <T> Stream<T> stream(Spliterator<T> spliterator, boolean parallel) { Objects.requireNonNull(spliterator); return new ReferencePipeline.Head<>(spliterator, StreamOpFlag.fromCharacteristics(spliterator), parallel); }
迭代器->流的示例
由于Iterator接口没有spliterator()方法所以需要使用Spliterators.spliteratorUnknownSize将Iterator转换为Spliterator
再使用StreamSupport.stream将Spliterator转换为Stream
package com.java265; import java.util.*; import java.util.stream.Collectors; import java.util.stream.StreamSupport; public class JavaStreamExample1 { public static void main(String[] args) { list<String> list = new ArrayList<>(); list.add("java265"); list.add("java"); list.add("c#"); list.add("spring boot"); list.add("python"); Iterator<String> iterator = list.iterator(); // Iterator -> Spliterators -> Stream -> List List<Integer> result = StreamSupport.stream( Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false) .map(x -> x.length()) .collect(Collectors.toList()); result.forEach(x -> System.out.println(x)); System.out.println(result.getClass()); } }
可迭代->流
由于Iterable接口拥有spliterator()方法所以非常方便就可以将其转换为Stream
package com.java265; import java.util.*; import java.util.stream.Collectors; import java.util.stream.StreamSupport; public class JavaStreamExample2 { public static void main(String[] args) { Iterable<Integer> iterable = Arrays.asList(88,99,110,222,333); // Iterable -> Spliterators -> Stream -> List List<Integer> result = StreamSupport.stream( iterable.spliterator(), false) .map(x -> x * 10) .collect(Collectors.toList()); result.forEach(x -> System.out.println(x)); System.out.println(result.getClass()); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。