Java 8 Convert Array to Stream

In this article we are going to see about Java 8 Convert Array to Stream Example

ArrayToStream.java

package com.ehowtonow.java8;

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

public class ArrayToStream {

 public static void main(String[] args) {
   String[] languages = {"Java", "C++", "Spring", "Hibernate", "R Language"};

         //Arrays.stream
         Stream arraysStream = Arrays.stream(languages);
         arraysStream.forEach(x -> System.out.println(x));

         //Stream.of
         Stream streamOf = Stream.of(languages);
         streamOf.forEach(x -> System.out.println(x));
         
         //For primitive array, the Arrays.stream and Stream.of will return different output.
         int[] intArray = {1, 2, 3, 4, 5};

         // 1. Arrays.stream -> IntStream
         IntStream intArraysStream = Arrays.stream(intArray);
         intArraysStream.forEach(x -> System.out.println(x));

         // 2. Stream.of-> Stream
         Stream intStreamOf = Stream.of(intArray);

         // Cant print Stream directly, convert / flat it to IntStream
         IntStream intStream2 = intStreamOf.flatMapToInt(x -> Arrays.stream(x));
         intStream2.forEach(x -> System.out.println(x));

 }

}

Output
Java
C++
Spring
Hibernate
R Language
Java
C++
Spring
Hibernate
R Language
1
2
3
4
5
1
2
3
4
5


Ask your questions in eHowToNow Forum

Post your technical, non-technical doubts, questions in our site. Get answer as soon as possible, meanwhile you can help others by answering, unanswered questions.
To Ask new Question : Ask Question
Check our existing discussions : Questions & Answers

  1. Java 8 Stream has already been operated upon or closed
  2. Java – Predicate Interface
  3. Java 8 New Features Overview
  4. Java 8 Functional Interface
  5. Java 8 Sort Map by Value
  6. Java – IntToLongFunction Interface
  7. Java – Collectors Class
  8. Java – BiPredicate Interface
  9. Java 8 convert List to Map example
  10. Java – DoublePredicate Interface
  11. java.util.function Package
  12. Java – IntFunction Interface
  13. java.util.stream Package
  14. Java – DoubleStream Interface
  15. Java – ObjLongConsumer Interface

Be the first to comment

Leave a Reply