103. Creating a Stream from an array

Once we create a Stream from an array, we have access to all the Stream API goodies. Therefore, this is a handy operation that is important to have in our tool belt.

Let's start with an array of strings (can be other objects as well):

String[] arr = {"One", "Two", "Three", "Four", "Five"};

The easiest way to create Stream from this String[] array is to rely on the Arrays.stream() method available starting with JDK 8:

Stream<String> stream = Arrays.stream(arr);

Or, if we need a stream from a sub-array, then simply add the range as arguments. For example, let's create a Stream from the elements that range between (0,2), which are one and two:

Stream<String> stream = Arrays.stream(arr, 0, 2);

The same cases, but passing through a List, can be written as follows:

Stream<String> stream = Arrays.asList(arr).stream();
Stream<String> stream = Arrays.asList(arr).subList(0, 2).stream();

Another solution relies on Stream.of() methods, as in the following straightforward examples:

Stream<String> stream = Stream.of(arr);
Stream<String> stream = Stream.of("One", "Two", "Three");

Creating an array from a Stream can be accomplished via the Stream.toArray() method. For example, a simple approach appears as follows:

String[] array = stream.toArray(String[]::new);

In addition, let's consider an array of primitives:

int[] integers = {2, 3, 4, 1};

In such a case, the Arrays.stream() method can help again, the only difference being that the returned result is of the IntStream type (this is the int primitive specialization of Stream):

IntStream intStream = Arrays.stream(integers);

But the IntStream class also provides an of() method that can be used as follows:

IntStream intStream = IntStream.of(integers);

Sometimes, we need to define a Stream of sequentially ordered integers with an incremental step of 1. Moreover, the size of the Stream should be equal to the size of an array. Especially for such cases, the IntStream method provides two methods—range(int inclusive, int exclusive) and rangeClosed(int startInclusive, int endInclusive):

IntStream intStream = IntStream.range(0, integers.length);
IntStream intStream = IntStream.rangeClosed(0, integers.length);

Creating an array from a Stream of integers can be accomplished via the Stream.toArray() method. For example, a simple approach appears as follows:

int[] intArray = intStream.toArray();

// for boxed integers
int[] intArray = intStream.mapToInt(i -> i).toArray();
Besides the IntStream specialization of Stream, JDK 8 provides specializations for long (LongStream) and double (DoubleStream).
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset