Return to site

Java Stream flatMap operation EXPLAINED

· java

flatMap flatten a number of streams into a single stream:
―Operation Stream<R> flatMap(Function<T, Stream<R>> f) merges streams, it combines these different streams into a single stream.
―There are primitive variants: flatMapToInt, flatMapToLong, and flatMapToDouble

FIRST

public class Order {
  private List<Product> items;
  public Stream<Product> items() {
    return items.stream();
  }
}

NEXT

List<Order> orders = fetchOrdersList();
double colaTotal = orders.stream()
                         .flatMap(order->order.items())
                         .filter(item->item.getName().equals("Cola"))
                         .mapToDouble(item->item.getPrice().douybleValue())
                         .sum();
Section image