The Wayback Machine - https://web.archive.org/web/20240930192109/https://www.geeksforgeeks.org/program-to-convert-boxed-array-to-stream-in-java/
Open In App

Program to convert Boxed Array to Stream in Java

Last Updated : 11 Dec, 2018
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

A boxed array is an array which is defined in the form of an object, instead of the primitives.
Example: int a = 4;

Examples:

Input: Array: [Geeks, forGeeks, A computer Portal]
Output: Stream: [Geeks, forGeeks, A computer Portal]

Input: Array: [1, 2, 3, 4, 5]
Output: Stream: [1, 2, 3, 4, 5]

Below are methods to convert Boxed Array to Stream in Java:

  1. Using Arrays.stream():

    Algorithm:

    1. Get the Array to be converted.
    2. Convert the array into Stream using Arrays.stream() method by passing the array as the parameter.
    3. Return the formed Stream

    Program:




    // Java Program to convert
    // Array to Stream
      
    import java.util.*;
    import java.util.stream.*;
      
    class GFG {
      
        // Generic function to convert 
        // an Array to Stream
        public static <T> Stream<T> 
                    convertArrayToStream(T array[])
        {
      
            // Return the converted Stream
            return Arrays.stream(array);
        }
      
        public static void main(String args[])
        {
            // Create an Array
            String array[] = { "Geeks", "forGeeks", 
                                        "A Computer Portal" };
      
            // Print the Array
            System.out.println("Array: "
                                    + Arrays.toString(array));
      
            // convert the Array to Stream
            Stream<String>
                stream = convertArrayToStream(array);
      
            // Print the Stream
            System.out.println("Stream: " 
                        + Arrays.toString(stream.toArray()));
        }
    }

    
    

    Output:

    Array: [Geeks, forGeeks, A computer Portal]
    Stream: [Geeks, forGeeks, A computer Portal]
    
  2. Using Stream.of(): Stream.of() method creates a Stream directly with the values or collection passed as the parameter.

    Algorithm:

    1. Get the Array to be converted.
    2. Convert the array into Stream using Stream.of() method by passing the array as the parameter.
    3. Return the formed Stream

    Program:




    // Java Program to convert
    // Array to Stream
      
    import java.util.*;
    import java.util.stream.*;
      
    class GFG {
      
        // Generic function to convert
        // an Array to Stream
        public static <T> Stream<T> 
                convertArrayToStream(T array[])
        {
      
            // Return the converted Stream
            return Stream.of(array);
        }
      
        public static void main(String args[])
        {
            // Create an Array
            String array[] = { "Geeks", "forGeeks", 
                                        "A Computer Portal" };
      
            // Print the Array
            System.out.println("Array: "
                                + Arrays.toString(array));
      
            // convert the Array to Stream
            Stream<String>
                stream = convertArrayToStream(array);
      
            // Print the Stream
            System.out.println("Stream: " 
                            + Arrays.toString(stream.toArray()));
        }
    }

    
    

    Output:

    Array: [Geeks, forGeeks, A computer Portal]
    Stream: [Geeks, forGeeks, A computer Portal]
    
  3. Using List.stream(): This is an indirect method in which the array is first converted into a List using Arrays.asList() method. Then the formed list is converted into a Stream using List.stream() method.

    Algorithm:

    1. Get the Array to be converted.
    2. Convert the array into List using Arrays.asList() method by passing the array as the parameter.
    3. Convert the formed List into Stream using List.stream() method.
    4. Return the formed Stream

    Program:




    // Java Program to convert
    // Array to Stream
      
    import java.util.*;
    import java.util.stream.*;
      
    class GFG {
      
        // Generic function to convert 
        // an Array to Stream
        public static <T> Stream<T> 
                    convertArrayToStream(T array[])
        {
      
            // Return the converted Stream
            return Arrays
                .asList(array)
                .stream();
        }
      
        public static void main(String args[])
        {
            // Create an Array
            String array[] = { "Geeks", "forGeeks", 
                                        "A Computer Portal" };
      
            // Print the Array
            System.out.println("Array: " 
                            + Arrays.toString(array));
      
            // convert the Array to Stream
            Stream<String>
                stream = convertArrayToStream(array);
      
            // Print the Stream
            System.out.println("Stream: " 
                       + Arrays.toString(stream.toArray()));
        }
    }

    
    

    Output:

    Array: [Geeks, forGeeks, A computer Portal]
    Stream: [Geeks, forGeeks, A computer Portal]
    


Previous Article
Next Article

Similar Reads

Java Program to Convert String to Char Stream Without Using Stream
Char stream defines the array of characters. In this article, we will learn the different types of methods for converting a String into a char stream in Java without using Stream. Let us see some methods one by one. ExamplesInput: String = HelloGeeksOutput: [H, e, l, l, o, G, e, e, k, s] Input: String = Introduction Output: [I, n, t, r, o, d, u, c,
4 min read
Difference between Stream.of() and Arrays.stream() method in Java
Arrays.stream() The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source. Example: Java Code // Java program to demonstrate Arrays.stream() method import java.uti
5 min read
Character Stream Vs Byte Stream in Java
A stream is a sequence of data. I/O Stream refers to a stream that is unlikely a method to sequentially access a file. I/O Stream means an input source or output destination representing different types of sources e.g. disk files. The java.io package provides classes that allow you to convert between Unicode character streams and byte streams of no
4 min read
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, t
3 min read
Program to convert Primitive Array to Stream in Java
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 sto
3 min read
foreach() loop vs Stream foreach() vs Parallel Stream foreach()
foreach() loopLambda operator is not used: foreach loop in Java doesn't use any lambda operations and thus operations can be applied on any value outside of the list that we are using for iteration in the foreach loop. The foreach loop is concerned over iterating the collection or array by storing each element of the list on a local variable and do
4 min read
Program to convert a Set to Stream in Java using Generics
Java Set is a part of java.util package and extends java.util.Collection interface. It does not allow the use of duplicate elements and at max can accommodate only one null element. A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. Below are the various methods to convert Set to St
3 min read
Program to convert a Map to a Stream in Java
A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. Below are various method to convert Map to Stream in Java: Converting complete Map<Key, Value> into Stream: This can be done with the help of Map.entrySet() method which returns a Set view of the mappings contained in this map
4 min read
Program to Convert List to Stream in Java
The List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector and Stack classes. A Stream is a sequence of objects that support
3 min read
Convert Stream to Set in Java
Below given are some methods which can be used to convert Stream to Set in Java. Method 1 : Using Collectors Stream collect() method takes elements from a stream and stores them in a collection.collect(Collector.toSet()) collects elements from a stream to a Set. Stream.collect() method can be used to collect elements of a stream in a container. The
3 min read
Convert a Set to Stream in Java
Set interface extends Collection interface and Collection has stream() method that returns a sequential stream of the collection. Below given are some examples to understand the implementation in a better way. Example 1 : Converting Integer HashSet to Stream of Integers. Java Code // Java code for converting // Set to Stream import java.util.*; imp
2 min read
Convert an Iterator to Stream in Java
Given an Iterator, the task is to convert it into Stream in Java. Examples: Input: Iterator = {1, 2, 3, 4, 5} Output: {1, 2, 3, 4, 5} Input: Iterator = {'G', 'e', 'e', 'k', 's'} Output: {'G', 'e', 'e', 'k', 's'} Approach: Get the Iterator. Convert the iterator to Spliterator using Spliterators.spliteratorUnknownSize() method. Convert the formed Spl
1 min read
Convert an Iterable to Stream in Java
Given an Iterable, the task is to convert it into Stream in Java. Examples: Input: Iterable = [1, 2, 3, 4, 5] Output: {1, 2, 3, 4, 5} Input: Iterable = ['G', 'e', 'e', 'k', 's'] Output: {'G', 'e', 'e', 'k', 's'} Approach: Get the Iterable. Convert the Iterable to Spliterator using Iterable.spliterator() method. Convert the formed Spliterator into S
1 min read
How to convert a Stream into a Map in Java
Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. In this article, the methods to convert a stream into a map is discussed. Method 1: Using Collectors.toMap() Function The Collectors.toMap() method take
6 min read
Convert String to Stream of Chars in Java
The StringReader class from the java.io package in Java can be used to convert a String to a character stream. When you need to read characters from a string as though it were an input stream, the StringReader class can be helpful in creating a character stream from a string. In this article, we will learn to convert a String to a char stream in Ja
2 min read
How to Convert String to Char Stream in Java without Using Library Functions?
In Java, we can convert a string to a char stream with a simple built-in method .toCharArray(). Here, we want to convert the string to a char stream without using built-in library functions. So, we will create an empty char array iterate it with string characters, and store the individual characters from the string to the char array one after the o
2 min read
Java Program to Find Maximum Odd Number in Array Using Stream and Filter
Java 8 introduced some great features like Stream and Filter which tremendously simplify tasks like reading data and performing operations like minimum, maximum, sum, and conditional check on them. In this program, we will get the maximum of all odd numbers from a list of integers with the help of the Java Stream and Filter method. Using Loops In t
3 min read
Program to Iterate over a Stream with Indices in Java 8
Given a Stream in Java, the task is to iterate over it with the help of indices. Examples: Input: Stream = [G, e, e, k, s] Output: [0 -> G, 1 -> e, 2 -> e, 3 -> k, 4 -> s] Input: Stream = [G, e, e, k, s, F, o, r, G, e, e, k, s] Output: [0 -> G, 1 -> e, 2 -> e, 3 -> k, 4 -> s, 5 -> F, 6 -> o, 7 -> r, 8 -> G, 9 -> e, 10 -> e, 11 -> k, 12 -> s] Method
2 min read
Java Program to Find the K'th largest element in a stream
Given an infinite stream of integers, find the k'th largest element at any point of time.Example: Input: stream[] = {10, 20, 11, 70, 50, 40, 100, 5, ...} k = 3 Output: {_, _, 10, 11, 20, 40, 50, 50, ...} Extra space allowed is O(k). Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. We have discussed different appro
4 min read
Java Stream | Collectors toCollection() in Java
Collectors toCollection(Supplier<C> collectionFactory) method in Java is used to create a Collection using Collector. It returns a Collector that accumulates the input elements into a new Collection, in the order in which they are passed. Syntax: public static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supp
2 min read
Array to Stream in Java
Prerequisite : Stream In Java Using Arrays.stream() : Syntax : public static <T> Stream<T> getStream(T[] arr) { return Arrays.stream(arr); } where, T represents generic type. Example 1 : Arrays.stream() to convert string array to stream. // Java code for converting string array // to stream using Arrays.stream() import java.util.*; impo
3 min read
Stream skip() method in Java with examples
Prerequisite : Streams in java The skip(long N) is a method of java.util.stream.Stream object. This method takes one long (N) as an argument and returns a stream after removing first N elements. skip() can be quite expensive on ordered parallel pipelines, if the value of N is large, because skip(N) is constrained to skip the first N elements in the
3 min read
Stream.concat() in Java
Stream.concat() method creates a concatenated stream in which the elements are all the elements of the first stream followed by all the elements of the second stream. The resulting stream is ordered if both of the input streams are ordered, and parallel if either of the input streams is parallel. Syntax : static <T> Stream<T> concat(Str
4 min read
Stream.distinct() in Java
distinct() returns a stream consisting of distinct elements in a stream. distinct() is the method of Stream interface. This method uses hashCode() and equals() methods to get distinct elements. In case of ordered streams, the selection of distinct elements is stable. But, in case of unordered streams, the selection of distinct elements is not neces
2 min read
Stream sorted() in Java
Stream sorted() returns a stream consisting of the elements of this stream, sorted according to natural order. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed. It is a stateful intermediate operation i.e, it may incorporate state from previously seen elements when processing new elements. Syntax
2 min read
Stream.max() method in Java with Examples
Stream.max() returns the maximum element of the stream based on the provided Comparator. A Comparator is a comparison function, which imposes a total ordering on some collection of objects. max() is a terminal operation which combines stream elements and returns a summary result. So, max() is a special case of reduction. The method returns Optional
3 min read
Stream sorted (Comparator comparator) method in Java
Stream sorted(Comparator comparator) returns a stream consisting of the elements of this stream, sorted according to the provided Comparator. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed. It is a stateful intermediate operation i.e, it may incorporate state from previously seen elements when p
3 min read
Stream min() method in Java with Examples
Stream.min() returns the minimum element of the stream based on the provided Comparator. A Comparator is a comparison function, which imposes a total ordering on some collection of objects. min() is a terminal operation which combines stream elements and returns a summary result. So, min() is a special case of reduction. The method returns Optional
2 min read
Stream generate() method in Java with examples
Stream generate(Supplier<T> s) returns an infinite sequential unordered stream where each element is generated by the provided Supplier. This is suitable for generating constant streams, streams of random elements, etc. Syntax : static <T> Stream<T> generate(Supplier<T> s) Where, Stream is an interface and T is the type of s
1 min read
Stream count() method in Java with examples
long count() returns the count of elements in the stream. This is a special case of a reduction (A reduction operation takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation). This is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect.
2 min read