.stream()vs Stream.of

时间:2016-10-05 12:40:37

标签: java java-8 java-stream

从集合中创建流的最佳方法是:

    final Collection<String> entities = someService.getArrayList();
  1. entities.stream();

  2. Stream.of(entities);

4 个答案:

答案 0 :(得分:23)

第二个不符合您的想法!它为您提供包含集合元素的流;相反,它将为您提供一个包含单个元素的流,这是集合本身(而不是其元素)。

如果您需要包含该集合元素的流,则必须使用entities.stream()

答案 1 :(得分:6)

1)

Stream<String> stream1 = entities.stream()

2)

Stream<Collection<String>> stream2 = Stream.of(entities)

所以使用1或2

Stream<String> stream3 = Stream.of("String1", "String2")

答案 2 :(得分:1)

我自己对此一直感到困惑,所以不妨将其留在这里以备将来参考:

import java.util.stream.IntStream;
import java.util.stream.Stream;

import static java.util.Arrays.*;
import static java.util.stream.Stream.*;

class Foo {
    void foo() {
        Stream<Foo> foo; 

        foo =     of(new Foo(), new Foo());
     // foo = stream(new Foo(), new Foo()); not possible

        foo =     of(new Foo[]{new Foo(), new Foo()});
        foo = stream(new Foo[]{new Foo(), new Foo()});

        Stream<Integer> integerStream; 

        integerStream =     of(1, 2);
     // integerStream = stream(1, 2); not possible

        integerStream =     of(new Integer[]{1, 2});
        integerStream = stream(new Integer[]{1, 2});

        Stream<int[]> intArrayStream =     of(new int[]{1, 2}); // count = 1!
        IntStream intStream          = stream(new int[]{1, 2}); // count = 2!
    }
}

答案 3 :(得分:1)

我们可以看一下源代码:

/**
 * Returns a sequential {@code Stream} containing a single element.
 *
 * @param t the single element
 * @param <T> the type of stream elements
 * @return a singleton sequential stream
 */
public static<T> Stream<T> of(T t) {
    return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
}

/**
 * Returns a sequential ordered stream whose elements are the specified values.
 *
 * @param <T> the type of stream elements
 * @param values the elements of the new stream
 * @return the new stream
 */
@SafeVarargs
@SuppressWarnings("varargs") // Creating a stream from an array is safe
public static<T> Stream<T> of(T... values) {
    return Arrays.stream(values);
}

Stream.of()一样,当输入变量是 array 时,它将调用第二个函数,并返回包含数组元素的流。当输入变量是列表时,它将调用第一个函数,您的输入集合将被视为单个元素,而不是集合。

所以正确的用法是:

List<Integer> list = Arrays.asList(3,4,5,7,8,9);
List<Integer> listRight = list.stream().map(i -> i*i).collect(Collectors.toList());

Integer[] integer = list.toArray(new Integer[0]);

List<Integer> listRightToo = Stream.of(integer).map(i ->i*i).collect(Collectors.toList());