Java Stream toArray() Example

1. Introduction

The Java Stream API provides a powerful abstraction for working with sequences of elements, including transformations and other operations. One common requirement is converting a stream of elements back into an array, and the toArray() method in the Stream API simplifies this process.

Key Points

1. toArray() can convert any stream to an array.

2. It returns an Object[] by default but can be overloaded to return arrays of a specific type.

3. Useful for integration with APIs or components that require arrays.

2. Program Steps

1. Import necessary classes.

2. Create a stream of elements.

3. Convert the stream to an array using toArray().

4. Print the array to verify contents.

3. Code Program

import java.util.Arrays;
import java.util.stream.Stream;

public class StreamToArrayExample {

    public static void main(String[] args) {
        // Step 2: Create a stream of elements
        Stream<String> stream = Stream.of("Java", "Python", "JavaScript", "Ruby");

        // Step 3: Convert the stream to an array
        String[] array = stream.toArray(String[]::new);

        // Step 4: Print the array
        System.out.println("Array from Stream: " + Arrays.toString(array));
    }
}

Output:

Array from Stream: [Java, Python, JavaScript, Ruby]

Explanation:

1. Stream.of("Java", "Python", "JavaScript", "Ruby") creates a stream containing several programming language names.

2. stream.toArray(String[]::new) converts the stream to an array of String. The method reference String[]::new provides a generator function to the toArray() method, which uses it to create the returned array.

3. Arrays.toString(array) is used to print the contents of the array, verifying that the stream elements have been correctly placed into an array.

Related Java Stream Examples

  1. Java Stream filter() Example
  2. Java Stream map() Example
  3. Java Stream flatMap() Example
  4. Java Stream distinct() Example
  5. Java Stream limit() Example
  6. Java Stream peek() Example
  7. Java Stream anyMatch() Example
  8. Java Stream allMatch() Example
  9. Java Stream noneMatch() Example
  10. Java Stream collect() Example
  11. Java Stream count() Example
  12. Java Stream findAny() Example
  13. Java Stream findFirst() Example
  14. Java Stream forEach() Example
  15. Java Stream min() Example
  16. Java Stream max() Example
  17. Java Stream reduce() Example
  18. Java Stream toArray() Example


Comments