forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFlatMapInStreams.java
67 lines (55 loc) · 1.62 KB
/
FlatMapInStreams.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.rampatra.java8;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author rampatra
* @version 17/02/2017
*/
public class FlatMapInStreams {
public static long countTotalIngredientsInAllDishes(List<Dish> dishes) {
return dishes.stream()
.map(Dish::getIngredients)
.flatMap(List::stream)
.count();
}
public static void main(String[] args) {
List<String> ingredients = new ArrayList<>();
ingredients.add("rice");
ingredients.add("chicken");
ingredients.add("haldi");
List<Dish> dishes = Arrays.asList(
new Dish("biriyani", 600, ingredients),
new Dish("pulao", 600, new ArrayList<>()));
// to show whether empty List is counted in flatMap
System.out.println(countTotalIngredientsInAllDishes(dishes));
}
}
class Dish {
private String name;
private int calories;
private List<String> ingredients;
public Dish(String name, int calories, List<String> ingredients) {
this.name = name;
this.calories = calories;
this.ingredients = ingredients;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCalories() {
return calories;
}
public void setCalories(int calories) {
this.calories = calories;
}
public List<String> getIngredients() {
return ingredients;
}
public void setIngredients(List<String> ingredients) {
this.ingredients = ingredients;
}
}