[英]What is the difference between .stream() and Stream.of?
哪个是从集合中创建流的最佳方法:
final Collection<String> entities = someService.getArrayList();
entities.stream();
Stream.of(entities);
第二个不符合你的想法! 它没有为您提供包含集合元素的流; 相反,它将为您提供一个包含单个元素的流,这是集合本身(而不是其元素)。
如果需要包含集合元素的流,则必须使用entities.stream()
。
1)
Stream<String> stream1 = entities.stream()
2)
Stream<Collection<String>> stream2 = Stream.of(entities)
所以使用1或2
Stream<String> stream3 = Stream.of("String1", "String2")
我自己一直对此感到困惑,所以我不妨把它留在这里以备将来参考:
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!
}
}
我们可以看看源代码:
/**
* 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()
,当输入变量是一个数组时 ,它将调用第二个函数,并返回一个包含数组元素的流。 当输入变量是一个列表时,它将调用第一个函数,并且您的输入集合将被视为单个元素,而不是集合。
所以正确的用法是:
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.