.stream() 和 Stream.of 有什么区别?

问题描述 投票:0回答:5

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

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

  2. Stream.of(entities);

java java-8 java-stream
5个回答
44
投票

第二个并没有像你想象的那样做!它“不”为您提供包含集合元素的流;相反,它会给你一个带有单个元素的流,该元素是集合本身(而不是它的元素)。 如果您需要一个包含集合元素的流,那么您必须使用

entities.stream()

    


7
投票

Stream<String> stream1 = entities.stream()

2)

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

所以使用 1,或 2

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



5
投票

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


当输入变量是
    数组
  1. 时,它将调用第二个函数,并返回包含数组元素的流。 当输入变量是
  2. list
  3. 时,它将调用first函数,并且您的输入集合将被视为单个元素,而不是集合。
  4. 所以正确的用法是:

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



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! } }



0
投票
Stream.of()

是通用的,而 Arrays.stream 不是: Arrays.stream()方法仅适用于int[]、long[]和double[]类型的原始数组,并分别返回IntStream、LongStream和DoubleStream。对于其他原始类型, Arrays.stream() 不起作用。另一方面,Stream.of()返回类型为T(Stream)的通用Stream。 因此,它可以与任何类型一起使用。

© www.soinside.com 2019 - 2024. All rights reserved.