| 
 | 1 | +package me.ramswaroop.java8;  | 
 | 2 | + | 
 | 3 | +import java.util.ArrayList;  | 
 | 4 | +import java.util.Arrays;  | 
 | 5 | +import java.util.List;  | 
 | 6 | + | 
 | 7 | +/**  | 
 | 8 | + * @author ramswaroop  | 
 | 9 | + * @version 17/02/2017  | 
 | 10 | + */  | 
 | 11 | +public class FlatMapInStreams {  | 
 | 12 | + | 
 | 13 | +    public static long countTotalIngredientsInAllDishes(List<Dish> dishes) {  | 
 | 14 | +        return dishes.stream().map(Dish::getIngredients).flatMap(List::stream).count();  | 
 | 15 | +    }  | 
 | 16 | + | 
 | 17 | +    public static void main(String[] a) {  | 
 | 18 | +        List<String> ingredients = new ArrayList<>();  | 
 | 19 | +        ingredients.add("rice");  | 
 | 20 | +        ingredients.add("chicken");  | 
 | 21 | +        ingredients.add("haldi");  | 
 | 22 | +        List<Dish> dishes = Arrays.asList(  | 
 | 23 | +                new Dish("biriyani", 600, ingredients),  | 
 | 24 | +                new Dish("biriyani", 600, new ArrayList<>()));  | 
 | 25 | +        // to show whether empty List is counted in flatMap  | 
 | 26 | +        System.out.println(countTotalIngredientsInAllDishes(dishes));   | 
 | 27 | +    }  | 
 | 28 | +}  | 
 | 29 | + | 
 | 30 | +class Dish {  | 
 | 31 | +    private String name;  | 
 | 32 | +    private int calories;  | 
 | 33 | +    private List<String> ingredients;  | 
 | 34 | + | 
 | 35 | +    public Dish(String name, int calories, List<String> ingredients) {  | 
 | 36 | +        this.name = name;  | 
 | 37 | +        this.calories = calories;  | 
 | 38 | +        this.ingredients = ingredients;  | 
 | 39 | +    }  | 
 | 40 | + | 
 | 41 | +    public String getName() {  | 
 | 42 | +        return name;  | 
 | 43 | +    }  | 
 | 44 | + | 
 | 45 | +    public void setName(String name) {  | 
 | 46 | +        this.name = name;  | 
 | 47 | +    }  | 
 | 48 | + | 
 | 49 | +    public int getCalories() {  | 
 | 50 | +        return calories;  | 
 | 51 | +    }  | 
 | 52 | + | 
 | 53 | +    public void setCalories(int calories) {  | 
 | 54 | +        this.calories = calories;  | 
 | 55 | +    }  | 
 | 56 | + | 
 | 57 | +    public List<String> getIngredients() {  | 
 | 58 | +        return ingredients;  | 
 | 59 | +    }  | 
 | 60 | + | 
 | 61 | +    public void setIngredients(List<String> ingredients) {  | 
 | 62 | +        this.ingredients = ingredients;  | 
 | 63 | +    }  | 
 | 64 | +}  | 
0 commit comments