Open In App

Java Program to convert Character Array to IntStream

Last Updated : 11 Dec, 2018
Improve
Improve
Like Article
Like
Save
Share
Report


Given a Character Array, the task is to convert this array into an IntStream containing the ASCII values of the character elements.

Examples:

Input: char[] = { 'G', 'e', 'e', 'k', 's' }
Output: 71, 101, 101, 107, 115

Input: char[] = { 'G', 'e', 'e', 'k', 's', 'F', 'o', 'r', 'G', 'e', 'e', 'k', 's' }
Output: 71, 101, 101, 107, 115, 70, 111, 114, 71, 101, 101, 107, 115

Algorithm:

  1. Get the Character Array to be converted.
  2. Convert it into Stream using Stream.of() method.
  3. Convert the formed Stream into IntStream using flatMapToInt() method.
  4. Print the formed IntStream.

Below is the implementation of the above approach:




// Java program to convert
// Character Array to IntStream
  
import java.util.stream.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Get the Character Array to be converted
        Character charArray[] = { 'G', 'e', 'e', 'k', 's' };
  
        // Convert charArray to IntStream
        IntStream
            intStream
            = Stream
  
                  // Convert charArray into Stream of characters
                  .of(charArray)
  
                  // Convert the Stream of characters into IntStream
                  .flatMapToInt(IntStream::of);
  
        // Print the elements of the IntStream
        System.out.println("IntStream:");
        intStream.forEach(System.out::println);
    }
}


Output:

IntStream:
71
101
101
107
115

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads