You can use Arrays.stream E.g.
Arrays.stream(array);
You can also use Stream.of
as mentioned by @fge , which looks like
public static<T> Stream<T> of(T... values) {
return Arrays.stream(values);
}
But note Stream.of(intArray)
will return Stream<int[]>
whereas Arrays.stream(intArr)
will return IntStream
providing you pass an array of type int[]
. So in a nutshell for primitives type you can observe the difference between 2 methods E.g.
int[] arr = {1, 2};
Stream<int[]> arr1 = Stream.of(arr);
IntStream stream2 = Arrays.stream(arr);
When you pass primitive array to Arrays.stream
, the following code is invoked
public static IntStream stream(int[] array) {
return stream(array, 0, array.length);
}
and when you pass primitive array to Stream.of
the following code is invoked
public static<T> Stream<T> of(T t) {
return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
}
Hence you get different results.
Updated: As mentioned by Stuart Marks comment
The subrange overload of Arrays.stream
is preferable to using Stream.of(array).skip(n).limit(m)
because the former results in a SIZED stream whereas the latter does not. The reason is that limit(m)
doesn't know whether the size is m or less than m, whereas Arrays.stream
does range checks and knows the exact size of the stream
You can read the source code for stream implementation returned by Arrays.stream(array,start,end)
here, whereas for stream implementation returned by Stream.of(array).skip().limit()
is within this method.
Given a Stream<String>
you can parse each item to an int
and wrap it into an Object[]
using:
strings
.filter(s -> s.trim().length() > 0)
.map(Integer::parseInt)
.map(i -> new Object[]{i})
Now to turn that result into a Object[][]
you can simply do:
Object[][] result = strings
.filter(s -> s.trim().length() > 0)
.map(Integer::parseInt)
.map(i -> new Object[]{i})
.toArray(Object[][]::new);
For the input:
final Stream<String> strings = Stream.of("1000", "999", "745", "123");
Output:
[[1000], [999], [745], [123]]
Best Answer
The easiest method is to use the
toArray(IntFunction<A[]> generator)
method with an array constructor reference. This is suggested in the API documentation for the method.What it does is find a method that takes in an integer (the size) as argument, and returns a
String[]
, which is exactly what (one of the overloads of)new String[]
does.You could also write your own
IntFunction
:The purpose of the
IntFunction<A[]> generator
is to convert an integer, the size of the array, to a new array.Example code:
Prints: