Converting Between Stream and Array in Java – 在Java中的流和数组之间的转换

最后修改: 2019年 5月 14日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

It’s common to need to convert various dynamic data structures into arrays.

通常需要将转换各种动态数据结构数组。

In this tutorial, we’ll demonstrate how to convert a Stream to an array and vice versa in Java.

在本教程中,我们将演示如何在Java中把一个Stream转换为数组,反之亦然。

2. Converting a Stream to an Array

2.将转换为数组

2.1. Method Reference

2.1.方法参考

The best way to convert a Stream into an array is to use Stream’s toArray() method:

Stream转换为数组的最佳方法是使用StreamtoArray()方法:

public String[] usingMethodReference(Stream<String> stringStream) {
    return stringStream.toArray(String[]::new);
}

Now, we can easily test if the conversion was successful:

现在,我们可以轻松地测试转换是否成功。

Stream<String> stringStream = Stream.of("baeldung", "convert", "to", "string", "array");
assertArrayEquals(new String[] { "baeldung", "convert", "to", "string", "array" },
    usingMethodReference(stringStream));

2.2. Lambda Expression

2.2.兰姆达表达式

Another equivalent is to pass a lambda expression to the toArray() method:

另一个等价物是将一个lambda表达式传递给toArray()方法。

public static String[] usingLambda(Stream<String> stringStream) {
    return stringStream.toArray(size -> new String[size]);
}

This would give us the same result as with using the method reference.

这将使我们得到与使用方法参考相同的结果。

2.3. Custom Class

2.3.自定义类

Or, we can go all out and create a full-blown class.

或者,我们可以全力以赴,创建一个完整的班级。

As we can see from the Stream documentation, it takes an IntFunction as an argument. It takes the array size as input and returns an array of that size.

正如我们从Stream文档中可以看到,它需要一个IntFunction作为参数。它将数组的大小作为输入,并返回一个该大小的数组。

Of course, IntFunction is an interface so we can implement it:

当然,IntFunction是一个接口,所以我们可以实现它。

class MyArrayFunction implements IntFunction<String[]> {
    @Override
    public String[] apply(int size) {
        return new String[size];
    }
};

We can then construct and use as normal:

然后我们就可以像平常一样构建和使用。

public String[] usingCustomClass(Stream<String> stringStream) {
    return stringStream.toArray(new MyArrayFunction());
}

Consequently, we can make the same assertion as earlier.

因此,我们可以做出与前面相同的断言。

2.4. Primitive Arrays

2.4.原始数组

In the previous sections, we explored how to convert a String Stream to a String array. In fact, we can perform the conversion this way for any Object and it would look very similar to the String examples above.

在前面的章节中,我们探讨了如何将String Stream转换为Stringarray。事实上,我们可以对任何Object进行这样的转换,它看起来与上面的String例子非常相似。

It’s a bit different for primitives, though. If we have a Stream of Integers that we want to convert to int[], for example, we first need to call the mapToInt() method:

不过,对于基元来说,这有点不同。例如,如果我们有一个StreamIntegers,我们想转换为int[],我们首先需要调用mapToInt()方法。

public int[] intStreamToPrimitiveIntArray(Stream<Integer> integerStream) {
    return integerStream.mapToInt(i -> i).toArray();
}

There’s also mapToLong() and mapToDouble() methods at our disposal. Also, please note that we didn’t pass any argument to the toArray() this time.

还有mapToLong()mapToDouble()方法供我们使用。另外,请注意,这次我们没有给toArray()传递任何参数。

Finally, let’s do the equality assertion and confirm that we’ve got our int array correctly:

最后,让我们做一下平等断言,确认我们的int数组是正确的。

Stream<Integer> integerStream = IntStream.rangeClosed(1, 7).boxed();
assertArrayEquals(new int[]{1, 2, 3, 4, 5, 6, 7}, intStreamToPrimitiveIntArray(integerStream));

What if we need to do the opposite, though? Let’s take a look.

但是,如果我们需要做相反的事情呢?让我们来看看。

3. Converting an Array to a Stream

3.将数组转换为Stream

We can, of course, go the other way, too. And Java has some dedicated methods for that.

当然,我们也可以反其道而行之。Java有一些专门的方法来做这件事。

3.1. Array of Objects

3.1.Objects的阵列

We can convert the array to a Stream using Arrays.stream() or Stream.of() methods:

我们可以使用Arrays.stream()Stream.of()方法将数组转换成Stream

public Stream<String> stringArrayToStreamUsingArraysStream(String[] stringArray) {
    return Arrays.stream(stringArray);
}

public Stream<String> stringArrayToStreamUsingStreamOf(String[] stringArray) {
    return Stream.of(stringArray);
}

We should note that in both cases, our Stream is of the same time as our array.

我们应该注意,在这两种情况下,我们的Stream与我们的数组是同一时间。

3.2. Array of Primitives

3.2.基元阵列

Similarly, we can convert an array of primitives:

同样地,我们可以转换一个基元数组。

public IntStream primitiveIntArrayToStreamUsingArraysStream(int[] intArray) {
    return Arrays.stream(intArray);
}

public Stream<int[]> primitiveIntArrayToStreamUsingStreamOf(int[] intArray) {
    return Stream.of(intArray);
}

But, in contrast to converting Objects arrays, there is an important difference. When converting primitives array, Arrays.stream() returns IntStream, while Stream.of() returns Stream<int[]>.

但是,与转换Objects数组相比,有一个重要区别。当转换基元数组时,Arrays.stream()返回IntStream,而Stream.of()返回Stream<int[]>/em>。

3.3. Arrays.stream vs. Stream.of

3.3.Arrays.streamStream.of的对比

In order to understand the differences mentioned in earlier sections, we’ll take a look at the implementation of the corresponding methods.

为了理解前面几节提到的差异,我们将看一下相应方法的实现。

Let’s first take a peek at Java’s implementation of these two methods:

让我们先来看看Java对这两个方法的实现。

public <T> Stream<T> stream(T[] array) {
    return stream(array, 0, array.length);
}

public <T> Stream<T> of(T... values) {
    return Arrays.stream(values);
}

We can see that Stream.of() is actually calling Arrays.stream() internally and that’s obviously the reason why we get the same results.

我们可以看到,Stream.of()实际上是在内部调用Arrays.stream(),这显然是我们得到相同结果的原因。

Now, we’ll check out the methods in the case when we want to convert an array of primitives:

现在,我们来看看在我们想转换基元数组的情况下的方法。

public IntStream stream(int[] array) {
    return stream(array, 0, array.length);
}

public <T> Stream<T> of(T t) {
    return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
}

This time, Stream.of() is not calling the Arrays.stream().

这一次,Stream.of()没有调用Arrays.stream()

4. Conclusion

4.总结

In this article, we saw how we can convert Streams to arrays in Java and the other way round. We also explained why we get different results when converting an array of Objects and when we use an array of primitives.

在这篇文章中,我们看到了如何在Java中把Streams转换为数组,以及反过来。我们还解释了为什么在转换Objects的数组和使用基元数组时,我们会得到不同的结果。

As always, complete source code can be found over on GitHub.

一如既往,完整的源代码可以在GitHub上找到over