对于中间操作和终端操作的定义,请看《JAVA8 stream接口 中间操作和终端操作》,这篇主要讲述的是stream的toArray操作,我们先看下函数的定义以及实现
Object[] toArray();
<A> A[] toArray(IntFunction<A[]> generator);
@Override
@SuppressWarnings("unchecked")
public final <A> A[] toArray(IntFunction<A[]> generator) {
// Since A has no relation to U (not possible to declare that A is an upper bound of U)
// there will be no static type checking.
// Therefore use a raw type and assume A == U rather than propagating the separation of A and U
// throughout the code-base.
// The runtime type of U is never checked for equality with the component type of the runtime type of A[].
// Runtime checking will be performed when an element is stored in A[], thus if A is not a
// super type of U an ArrayStoreException will be thrown.
@SuppressWarnings("rawtypes")
IntFunction rawGenerator = (IntFunction) generator;
return (A[]) Nodes.flatten(evaluateToArrayNode(rawGenerator), rawGenerator)
.asArray(rawGenerator);
}
@Override
public final Object[] toArray() {
return toArray(Object[]::new);
}
可以看到,返回Object[],没有传参数的toArray,在具体的实现中,也是调用了
public final <A> A[] toArray(IntFunction<A[]> generator)
重载的toArray的实现,传入了一个Object的数组
下面我们通过案例,看下具体的使用
List<String> strs = Arrays.asList("a", "b", "c");
String[] dd = strs.stream().toArray(str -> new String[strs.size()]);
String[] dd1 = strs.stream().toArray(String[]::new);
Object[] obj = strs.stream().toArray();
String[] dd2 = strs.toArray(new String[strs.size()]);
Object[] obj1 = strs.toArray();
可以看到,前三个,是调用的stream的toArray的函数,以及一些用法,后面的两个,是直接调用的List接口的toArray函数,List接口里的,只是顺带提了一下,用法就是这样,请大家自己get吧
上一篇《java8 stream接口 终端操作 forEachOrdered和forEach》 下一篇《 java8 stream接口 终端操作 min,max,findFirst,findAny操作》