728x90 AdSpace

Sunday, 2 July 2017

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.javatutorialcorner.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
Annamalai Thangaraj

Annamalai is working as Technical Lead in Leading Telecom company with 5+ years experience in Identity and Access Management , Telecom and Networks, BigData, Java, Spring, Struts, Hibernate, AngularJS, and Enterprise Web Application Development.

Website: Java Tutorials Corner

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: Java 8 - Convert Array to Stream Rating: 5 Reviewed By: Annamalai Thangaraj