Java Program to convert Character Array to IntStream


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


Output:

IntStream:
71
101
101
107
115


My Personal Notes arrow_drop_up

Technical Content Engineer at GeeksForGeeks

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.