Java 8 flatMap Example

By Arvind Rai, May 31, 2016
On this page we will provide java 8 flatMap example. We will discuss here Stream.flatMap and Optional.flatMap() method. Stream.flatMap() returns the stream which will contain the elements obtained by replacement of each element of the source stream by a mapping function and and flattens the result. Mapping function will produce stream and each mapped stream is closed after applying the mapping. It is useful to apply statistical function on the stream of objects and can be coded in a single line. Optional.flatMap() applies the Optional-bearing mapping function to it if value is present. Now find the examples for flatMap with different scenarios.
According to the Java Doc, Stream.flatMap() method signature is as given below.
<R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)
 
Optional.flatMap() method signature is as given below.
public <U> Optional<U> flatMap(Function<? super T,Optional<U>> mapper)
 
For the primitive data types, java provides flatMapToInt(), flatMapToLong() and flatMapToDouble() API.

Stream flatMap with List

Here we have a List of writers. Each writer has list of books. Using Stream.flatMap() we will get stream of books from all writers. And then we will find the book with highest price. We will understand it step wise.
1. Stream of writers.
{
   {"Mohan",
    {
      {10,"AAA"}, {20,"BBB"}
    }
   },
   {"Sohan",
    {
      {30,"XXX"}, {15,"ZZZ"}
    }
   }
}
2. After flatMap(writer -> writer.getBooks().stream()), find the stream of books.
{      
   {10,"AAA"}, 
   {20,"BBB"},
   {30,"XXX"}, 
   {15,"ZZZ"}
}
Here the result has been flattened by flatMap().

3. After max(new BookComparator()), find the book with maximum price.
{30,"XXX"}

Now find the code.
FlatmapWithList.java
package com.concretepage;
import java.util.Arrays;
import java.util.List;
public class FlatmapWithList {
    public static void main(String[] args) {
    	List<Book> books = Arrays.asList(new Book(10, "AAA"), new Book(20, "BBB"));
    	Writer w1 = new Writer("Mohan", books);
    	books = Arrays.asList(new Book(30, "XXX"), new Book(15, "ZZZ"));
    	Writer w2 = new Writer("Sohan", books);    	
    	List<Writer> writers = Arrays.asList(w1, w2);
    	Book book = writers.stream().flatMap(writer -> writer.getBooks().stream())
    			.max(new BookComparator()).get();
    	System.out.println("Name:"+book.getName()+", Price:"+ book.getPrice() );
    }
}  
Writer.java
package com.concretepage;
import java.util.List;
public class Writer {
	private String name;
	private List<Book> books;
	public Writer(String name, List<Book> books) {
		this.name = name;
		this.books = books;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public List<Book> getBooks() {
		return books;
	}
	public void setBooks(List<Book> books) {
		this.books = books;
	}
} 
Book.java
package com.concretepage;
public class Book {
	private int price;
	private String name;
	public Book(int price, String name) {
		this.price = price;
		this.name = name;
	}
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
} 
BookComparator.java
package com.concretepage;
import java.util.Comparator;
public class BookComparator implements Comparator<Book> {
	@Override
	public int compare(Book b1, Book b2) {
		if (b1.getPrice() > b2.getPrice()) {
			return 1;
		} else if (b1.getPrice() == b2.getPrice()) {
			return 0;
		} else {
			return -1;
		}
	}
} 
Find the output.
Name:XXX, Price:30
 

Stream flatMap with List of Lists

Here we will use flatMap with list of lists. We are creating two lists and each list is containing the objects of Book. Finally I am adding these two lists in a third list. We will find out the book with minimum price.
FlatmapWithListOfList.java
package com.concretepage;
import java.util.Arrays;
import java.util.List;
public class FlatmapWithListOfList {
    public static void main(String[] args) {
    	List<Book> list1 = Arrays.asList(new Book(10, "AAA"), new Book(20, "BBB"));
    	List<Book> list2 = Arrays.asList(new Book(30, "XXX"), new Book(15, "ZZZ"));
    	List<List<Book>> finalList = Arrays.asList(list1, list2);
    	Book book = finalList.stream().flatMap(list -> list.stream()).min(new BookComparator()).get();
    	System.out.println("Name:"+book.getName()+", Price:"+ book.getPrice() );
    }
} 
Find the output.
Name:AAA, Price:10
 

Stream flatMap with Array

Here we will use flatMap with array. I am creating a two dimensional array with integer data. Finally we will find out even numbers.
1. Sample Array
{{1,2},{3,4},{5,6}}
2. After flatMap(row -> Arrays.stream(row))
{1,2,3,4,5,6}
3. After filter(num -> num%2 == 0)
{2,4,6}
Now find the example.
FlatMapWithArray.java
package com.concretepage;
import java.util.Arrays;
public class FlatMapWithArray {
	public static void main(String[] args) {
		Integer[][] data = {{1,2},{3,4},{5,6}};
		Arrays.stream(data).flatMap(row -> Arrays.stream(row)).filter(num -> num%2 == 0).
		forEach(System.out::println);
	}
} 
Find the output.
2
4
6 

Stream flatMap with Array of Objects

Here we will provide the example of flatMap with array of objects. We will create two dimensional array of Writer. This class will contain list of books. We will find the book with maximum price.
FlatMapWithArrayOfObject.java
package com.concretepage;
import java.util.Arrays;
import java.util.List;
public class FlatMapWithArrayOfObject {
    public static void main(String[] args) {
    	List<Book> books = Arrays.asList(new Book(10, "AAA"), new Book(20, "BBB"));
    	Writer w1 = new Writer("Mohan", books);
    	books = Arrays.asList(new Book(30, "CCC"), new Book(15, "DDD"));
    	Writer w2 = new Writer("Sohan", books);    	
    	books = Arrays.asList(new Book(45, "EEE"), new Book(25, "FFF"));
    	Writer w3 = new Writer("Vikas", books);
    	books = Arrays.asList(new Book(5, "GGG"), new Book(15, "HHH"));
    	Writer w4 = new Writer("Ramesh", books);
        Writer[][] writerArray = {{w1,w2},{w3,w4}};
        
        Book book = Arrays.stream(writerArray).flatMap(row -> Arrays.stream(row)).
            flatMap(writer -> writer.getBooks().stream()).max(new BookComparator()).get();
        
        System.out.println("Name:"+book.getName()+", Price:"+ book.getPrice() );
    }
} 
Find the output.
Name:EEE, Price:45
 

Stream flatMap with Files.lines()

Files.lines() has been introduced in Java 8. It reads all the lines of the file as a stream. Here in our example we have a file with some lines. We will store all the words in a list and print it out.
info.txt
My name is Mohan
Country is India  
FlatMapWithFile.java
package com.concretepage;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class FlatMapWithFile {
	public static void main(String[] args) {
	    Stream<String> lines = null;
	    try {
		lines = Files.lines(Paths.get("D:/cp/info.txt"), StandardCharsets.UTF_8);
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	    Stream<String> stream = lines.flatMap(line -> Stream.of(line.split(" +")));
	    List<String> words = new ArrayList<>();
	    stream.forEach(w->words.add(w));
	    words.forEach(w -> System.out.println(w));
	}
} 
Find the output.
My
name
is
Mohan
Country
is
India 

Optional flatMap

Optional has been introduced in Java 8. It behaves like a container that may keep non-null value. It handles NullPointerException. flatMap is applied only if value is present. Find the example.
OptionalflatMap.java
package com.concretepage;
import java.util.Optional;
public class OptionalflatMap {
    public static void main(String[] args) {
        Optional<PrimeMinister> primeMinister = Optional.of(new PrimeMinister("Narendra Modi", 65));
        Optional<Country> country = Optional.of(new Country(primeMinister));
        Optional<Person> person = Optional.of(new Person(country));
        String pmName= person.flatMap(Person::getCountry).flatMap(Country::getPrimeMinister)
                .map(PrimeMinister::getName).orElse("None");
        System.out.println(pmName);
   }
} 
Country.java
package com.concretepage;
import java.util.Optional;
public class Country {
	Optional<PrimeMinister> primeMinister;
        public Country(){}
        public Country(Optional<PrimeMinister> primeMinister){
                this.primeMinister = primeMinister;
        }
	public Optional<PrimeMinister> getPrimeMinister() {
		return primeMinister;
	}
	public void setPrimeMinister(Optional<PrimeMinister> primeMinister) {
		this.primeMinister = primeMinister;
	}
} 
Person.java
package com.concretepage;
import java.util.Optional;
public class Person {
	Optional<Country> country;
        public Person(){}
        public Person(Optional<Country> country){
        this.country = country;
        }
	public Optional<Country> getCountry() {
		return country;
	}
	public void setCountry(Optional<Country> country) {
		this.country = country;
	}
} 
Find the output.
Narendra Modi
 

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us