Java Stream flatMap Method: Examples and How to Use it

Java Stream flatMap Method: Examples and How to Use it

The "flatMap" method is a powerful tool in the Java Stream API. It allows you to transform each element of a stream into a new stream of elements, and then combine all those streams into a single stream. In this article, we'll take a closer look at how the "flatMap" method works and how to use it in your Java code.

Before we dive into examples of using "flatMap", let's take a closer look at how it works.

The "flatMap" method takes a function that maps each element of a stream to a new stream. The resulting stream of streams is then flattened into a single stream by concatenating the individual streams together. This means that each element of the resulting stream is an element of one of the individual streams that was created by the mapping function.

Here's the signature of the "flatMap" method:

<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)

The "mapper" parameter is the function that maps each element of the stream to a new stream. The resulting stream of streams is then flattened into a single stream of type "R".

Now that we understand how the "flatMap" method works, let's look at some examples of using it in Java code.

Example 1: Flattening a list of lists

Suppose you have a list of lists, where each inner list contains a set of integers. You want to find the sum of all the integers in all the inner lists. Here's how you can use "flatMap" to achieve this:

import java.util.Arrays
import java.util.List;


public class Example {
    public static void main(String[] args) {
        List<List<Integer>> listOfLists = Arrays.asList(
                Arrays.asList(1, 2, 3),
                Arrays.asList(4, 5, 6),
                Arrays.asList(7, 8, 9)
        );


        int sum = listOfLists.stream()
                .flatMap(List::stream)
                .mapToInt(Integer::intValue)
                .sum();


        System.out.println(sum); // Output: 45
    }
}

In the code above, we have a list of lists "listOfLists", which contains three inner lists. We use "flatMap" to flatten the list of lists into a single stream of integers, and then we use "mapToInt" to convert the stream of integers into an "IntStream" so we can use the sum method to find the total sum.

Note that we're using the "List::stream" method reference in "flatMap" to flatten the list of lists. This method reference returns a stream of the elements in the inner list, which allows us to combine all the elements from the inner lists into a single stream of integers.

Example 2: Flattening a list of orders

Suppose you have a list of orders, where each order contains a list of line items. You want to get a list of all the unique products that have been ordered. Here's how you can use "flatMap" to achieve this:

import java.util.Arrays
import java.util.List;
import java.util.stream.Collectors;


public class FlatMapExample {


    public static void main(String[] args) {
        
        Order order1 = new Order("123", Arrays.asList(
                new Product("Apple", 1),
                new Product("Orange", 2),
                new Product("Banana", 3)));
        
        Order order2 = new Order("456", Arrays.asList(
                new Product("Apple", 4),
                new Product("Grape", 5),
                new Product("Banana", 6)));
        
        List<Order> orders = Arrays.asList(order1, order2);
        
        List<Product> uniqueProducts = orders.stream()
                .flatMap(order -> order.getProducts().stream())
                .distinct()
                .collect(Collectors.toList());
        
        System.out.println(uniqueProducts);
    }
}


class Order {
    
    private String orderId;
    private List<Product> products;
    
    public Order(String orderId, List<Product> products) {
        this.orderId = orderId;
        this.products = products;
    }
    
    public String getOrderId() {
        return orderId;
    }
    
    public List<Product> getProducts() {
        return products;
    }
}


class Product {
    
    private String name;
    private int id;
    
    public Product(String name, int id) {
        this.name = name;
        this.id = id;
    }
    
    public String getName() {
        return name;
    }
    
    public int getId() {
        return id;
    }
    
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Product product = (Product) o;
        return id == product.id;
    }
    
    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
    
    @Override
    public String toString() {
        return "Product{" +
                "name='" + name + '\'' +
                ", id=" + id +
                '}';
    }
}

This code creates two "Order" objects, each with a list of "Product" objects. It then creates a list of "Order" objects and uses the "flatMap" method to create a new stream of "Product" objects. It then uses the "distinct" method to filter out any duplicate products, and finally collects the result into a new list.

When you run this code, the output should be:

[Product{name='Apple', id=1}, Product{name='Orange', id=2}, Product{name='Banana', id=3}, Product{name='Apple', id=4}, Product{name='Grape', id=5}, Product{name='Banana', id=6}]

This shows that the "flatMap" method has successfully flattened the list of "Product" objects from the two orders into a single stream, and the distinct method has filtered out any duplicates. The resulting list contains only the unique "Product" objects.

In this article, we've covered how the "flatMap" method works, and we've given examples of how to use it to flatten a list of lists and to get a list of unique products from a list of orders.

The "flatMap" method is a powerful tool in the Java Stream API that allows you to transform each element of a stream into a new stream of elements, and then combine all those streams into a single stream. It's particularly useful for flattening nested collections and creating new collections that are derived from existing collections.

When you're using "flatMap", it's important to remember that the function you provide should return a stream, not just a collection or array. This allows "flatMap" to flatten the streams into a single stream.

Overall, "flatMap" is a great addition to the Java Stream API, and it's worth taking the time to understand how it works so you can use it effectively in your own code.




Sarang Ghamandi

Senior Project Engineer at Wipro Technology Ltd

1 年

Very well explained Nikhil

回复

For the second example I will like to use new Product("Apple", 1), new Product("Grape", 4), new Product("Banana", 3))); to highlight the functionality of distinct [{"name":"Apple","id":1},{"name":"Orange","id":2},{"name":"Banana","id":3},{"name":"Grape","id":4}]

回复
Vikas Srivastava

Principle Software Engineer | Passionate about bringing technology into life.

1 年

Very well explained Nikhil

要查看或添加评论,请登录

Nikhil Gargatte的更多文章

社区洞察

其他会员也浏览了