Home  >  Java 8

Java 8 Stream: flatMap, generate and Stream.of Example

By Arvind Rai, November 22, 2014
On this page we will learn java 8 Stream.flatMap(), Stream.generate() and Stream.of() methods. These methods return stream object. Stream.flatMap() maps a function to all elements of the stream. Stream.generate() method generates infinite number of elements as a stream. Stream.of() method returns stream object for the element passed as an argument. We will see the use of these methods by the example.

Stream.of()

Stream.of() is a method which returns sequential ordered stream. We can pass any number of elements comma separated and will get stream instance.
StreamOfDemo.java
package com.concretepage.util.stream;
import java.util.stream.Stream;
public class StreamOfDemo {
    public static void main(String[] args) {
        Stream.of("Ram","Shyam","Mohan").forEach(s->System.out.println(s));
    }
} 
Find the output.
Ram
Shyam
Mohan 

Stream.flatMap()

Stream.flatMap() returns the stream object. We need to pass a function as an argument. Function will be applied to each element of stream and result will be flattened..
FlatMapDemo.java
package com.concretepage.util.stream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class FlatMapDemo {
    public static void main(String[] args) {
        List<String> list1 = Arrays.asList("AAA","BBB");
        List<String> list2 = Arrays.asList("CCC","DDD");
        Stream.of(list1,list2).flatMap(list -> list.stream()).forEach(s->System.out.println(s));
    }
} 
Find the output.
AAA
BBB
CCC
DDD 
For more detail on flatMap, find the link Java 8 flatMap Example.

Stream.generate()

Stream.generate() returns infinite sequential and unordered stream. We need to pass supplier to generate element.
GenerateDemo.java
package com.concretepage.util.stream;
import java.util.stream.Stream;
public class GenerateDemo {
    public static void main(String[] args) {
        Item item =new Item("AA");
        Stream<String> stream = Stream.generate(item::getName);
        stream.forEach(s->System.out.println(s));
    }
} 
Find the Item class.
Item.java
package com.concretepage.util.stream;
public class Item {
    private String name;
    public Item(String name){     
        this.name=name;
    }
    public String getName() {
        return name;
    }
} 
Find the output.
AA
AA
AA
AA
AA
AA
----
----
 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us