Wednesday, July 3, 2024
HomeLanguagesJavaProgram to Convert Stream to an Array in Java

Program to Convert Stream to an Array in Java

A Stream is a sequence of objects that support various methods which can be pipelined to produce the desired result.

An array is a group of like-typed variables that are referred to by a common name. An array can contain primitives data types as well as objects of a class depending on the definition of the array. In case of primitives data types, the actual values are stored in contiguous memory locations. In case of objects of a class, the actual objects are stored in heap segment.

Below are various methods to convert Stream into an Array:

  1. Using toArray(): Stream provides toArray() method that returns an array containing the elements of the stream in the form of Object array.

    Syntax:

    stream.toArray()

    Algorithm:

    1. Get the Stream
    2. Convert Stream into an Array using Stream.toArray() method.
    3. The obtained array is of type Object[]
    4. Return the Array Object[]

    Program:




    // Java Program to convert
    // Stream to array in Java 8
      
    import java.util.*;
    import java.util.stream.*;
    import java.util.function.Function;
      
    class GFG {
      
        // Function to convert Stream to Array
        public static <T> Object[] convertStreamToArray(Stream<T> stream)
        {
            return stream.toArray();
        }
      
        public static void main(String args[])
        {
            // Create a stream of integers
            Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
      
            // Convert Stream to array
            Object[] array = convertStreamToArray(stream);
      
            // Print the array of stream
            System.out.println("Array from Stream: "
                               + Arrays.toString(array));
        }
    }

    
    
    Output:

    Array from Stream: [1, 2, 3, 4, 5]
    
  2. Using toArray(IntFunction generator): This method returns an array containing the elements of this stream, using the provided generator function to allocate the returned array, as well as any additional arrays that might be required for a partitioned execution or for resizing.

    Syntax:

    <A> A[] toArray(IntFunction<A[]> generator)

    Algorithm:

    1. Get the Stream
    2. Convert Stream into an Array using Stream.toArray() method by passing Object[]::new as the generator function to allocate the returned array.
    3. The obtained array is of type Object[]
    4. Return the Array Object[]

    Program:




    // Java Program to convert
    // Stream to array in Java 8
      
    import java.util.*;
    import java.util.stream.*;
    import java.util.function.Function;
      
    class GFG {
      
        // Function to convert Stream to Array
        public static <T> Object[] convertStreamToArray(Stream<T> stream)
        {
            return stream.toArray(Object[] ::new);
        }
      
        public static void main(String args[])
        {
      
            // Create a stream of integers
            Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
      
            // Convert Stream to array
            Object[] array = convertStreamToArray(stream);
      
            // Print the array of stream
            System.out.println("Array from Stream: "
                               + Arrays.toString(array));
        }
    }

    
    
    Output:

    Array from Stream: [1, 2, 3, 4, 5]
    
  3. Stream to int[] using mapToInt(): Java 8 Stream API provides mapToInt() method that returns an IntStream consisting of the results of applying the given function to the elements of this stream. This is an intermediate operation. The obtained IntStream is then converted into int[] using toArray().

    Algorithm:

    1. Get the Stream of Integers
    2. Convert Stream into an IntStream using Stream.mapToInt() method.
    3. Convert the obtained IntStream into int[] using toArray()
    4. The obtained array is of type Integer
    5. Return the Array int[]

    Program:




    // Java Program to convert
    // Stream to array in Java 8
      
    import java.util.*;
    import java.util.stream.*;
    import java.util.function.Function;
      
    class GFG {
      
        // Function to convert Stream to Array
        public static int[] convertStreamToArray(Stream<Integer> stream)
        {
            return stream.mapToInt(Integer::intValue).toArray();
        }
      
        public static void main(String args[])
        {
      
            // Create a stream of integers
            Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
      
            // Convert Stream to array
            int[] array = convertStreamToArray(stream);
      
            // Print the array of stream
            System.out.println("Array of Integer from Stream: "
                               + Arrays.toString(array));
        }
    }

    
    
    Output:

    Array of Integer from Stream: [1, 2, 3, 4, 5]
    

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments