Java 8 Iterator转为Stream

作者 | 2020年4月18日

在Java8中,我们可以使用StreamSupport.stream方法把Iterator转为Stream

// Iterator -> Spliterators -> Stream
  Stream<String> stream = StreamSupport.stream(
                Spliterators.spliteratorUnknownSize(
                        iterator,
                        Spliterator.ORDERED)
                , false);

下面是StreamSupport.stream方法的签名,它接受一个Spliterator参数。

StreamSupport.java

  public static <T> Stream<T> stream(Spliterator<T> spliterator, boolean parallel) {
      Objects.requireNonNull(spliterator);
      return new ReferencePipeline.Head<>(spliterator,
                                          StreamOpFlag.fromCharacteristics(spliterator),
                                          parallel);
  }

1. Iterator转Stream

Iterator接口没有spliterator()方法,所有我们需要使用Spliterators.spliteratorUnknownSize方法把Iterator转为Spliterator,再使用Iterator -> Spliterators -> Stream方法把Spliterator转为Stream

Iterator -> Spliterators -> Stream

下面的代码演示了如何把Iterator转为Stream

JavaStreamExample1.java

package com.mkyong;

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("mkyong");
        list.add("java");
        list.add("kotlin");
        list.add("spring boot");
        list.add("android");

        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());

    }

}

输出

6
4
6
11
7
class java.util.ArrayList

2. Iterable转Stream

因为Iterable接口有spliterator()方法,所有它可以很容易的转为Stream

JavaStreamExample2.java

package com.mkyong;

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(1, 2, 3, 4, 5);

        // 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());

    }

}

输出

10
20
30
40
50

发表评论

电子邮件地址不会被公开。 必填项已用*标注