Create a Stream from an Array in Java



Write a program that creates a Stream from the given array in Java

Create a Stream from an Array in Java

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

public class Main {

    public static void main(String[] args) {

        // String array
        String[] arr = {"One", "Two", "Three", "Four", "Five"};

        // array to Stream
        Stream<String> stream1 = Arrays.stream(arr);
        
        stream1.forEach((item) ->{
        	System.out.println(item);
        });
        
        Stream<String> stream2 = Arrays.stream(arr, 0, 2);
        
        stream2.forEach((item) ->{
        	System.out.println(item);
        });
        
        Stream<String> stream3 = Arrays.asList(arr).stream();
        stream3.forEach((item) ->{
        	System.out.println(item);
        });
        
        Stream<String> stream4 = Arrays.asList(arr).subList(0, 2).stream();
        stream4.forEach((item) ->{
        	System.out.println(item);
        });
        
        Stream<String> stream5 = Stream.of(arr);
        stream5.forEach((item) ->{
        	System.out.println(item);
        });
        
        Stream<String> stream6 = Stream.of("One", "Two", "Three");
        stream6.forEach((item) ->{
        	System.out.println(item);
        });
    }
}

Output:

One
Two
Three
Four
Five
One
Two
One
Two
Three
Four
Five
One
Two
One
Two
Three
Four
Five
One
Two
Three

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments