In this article we are going to see about Java 8 - Convert Array to Stream Example
ArrayToStream.java
Output
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 StreamarraysStream = 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
0 comments:
Post a Comment