Friday 20 October 2017

How to generate stream using generate and iterate methods of Java 8 streams | Streams in Java 8


Click here to watch in Youtube : 
https://www.youtube.com/watch?v=TIFp_3pmDkw&list=UUhwKlOVR041tngjerWxVccw

StreamDemo1.java
import java.util.Arrays;
import java.util.stream.Stream;
/**
 * Generate Stream using Stream.generate()
 */
public class StreamDemo1
{
    public static void main(String[] args)
    {
        Stream<String> stream = Stream.generate(() -> "welcome").limit(5);
        String[] strArr = stream.toArray(String[]::new);
        System.out.println(Arrays.toString(strArr));
    }

}
Output
[welcome, welcome, welcome, welcome, welcome]

StreamDemo2.java
import java.util.stream.Stream;
/**
 * Generate Stream using Stream.iterate().
 */
public class StreamDemo2
{
    public static void main(String[] args)
    {
        Stream<Long> iterateNumbers = Stream.iterate(1L, n -> n + 10).limit(5);
        iterateNumbers.forEach(System.out::println);
    }

}
Output
1
11
21
31
41

StreamDemo3.java
import java.util.regex.Pattern;
/**
 * Generate Stream from APIs like Regex.
 */
public class StreamDemo3
{
    public static void main(String[] args)
    {
        String str = "Welcome,to,India";
        Pattern.compile(",").splitAsStream(str).forEach(System.out::println);
    }

}
Output
Welcome
to
India

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/StreamDemo_generate_iterate_regex.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/StreamDemo_generate_iterate_regex

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/a9fa8aa6476993bce8a79f4d0e8f1799d1d35a7f/BasicJava/StreamDemo_generate_iterate_regex/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment