Skip to content

Commit 8028e09

Browse files
committed
'update'
1 parent 074b4e5 commit 8028e09

File tree

5 files changed

+144
-114
lines changed

5 files changed

+144
-114
lines changed

src/main/java/lambdasinaction/chap6/Grouping.java

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ enum CaloricLevel { DIET, NORMAL, FAT };
1313
public static void main(String ... args) {
1414
System.out.println("Dishes grouped by type: " + groupDishesByType());
1515
System.out.println("Dish names grouped by type: " + groupDishNamesByType());
16-
System.out.println("Dish tags grouped by type: " + groupDishTagsByType());
17-
System.out.println("Caloric dishes grouped by type: " + groupCaloricDishesByType());
16+
// System.out.println("Dish tags grouped by type: " + groupDishTagsByType());
17+
// System.out.println("Caloric dishes grouped by type: " + groupCaloricDishesByType());
1818
System.out.println("Dishes grouped by caloric level: " + groupDishesByCaloricLevel());
1919
System.out.println("Dishes grouped by type and caloric level: " + groupDishedByTypeAndCaloricLevel());
2020
System.out.println("Count dishes in groups: " + countDishesInGroups());
@@ -32,14 +32,14 @@ private static Map<Dish.Type, List<String>> groupDishNamesByType() {
3232
return menu.stream().collect(groupingBy(Dish::getType, mapping(Dish::getName, toList())));
3333
}
3434

35-
private static Map<Dish.Type, Set<String>> groupDishTagsByType() {
36-
return menu.stream().collect(groupingBy(Dish::getType, flatMapping(dish -> dishTags.get( dish.getName() ).stream(), toSet())));
37-
}
38-
39-
private static Map<Dish.Type, List<Dish>> groupCaloricDishesByType() {
35+
// private static Map<Dish.Type, Set<String>> groupDishTagsByType() {
36+
// return menu.stream().collect(groupingBy(Dish::getType, flatMapping(dish -> dishTags.get( dish.getName() ).stream(), toSet())));
37+
// }
38+
//
39+
// private static Map<Dish.Type, List<Dish>> groupCaloricDishesByType() {
4040
// return menu.stream().filter(dish -> dish.getCalories() > 500).collect(groupingBy(Dish::getType));
41-
return menu.stream().collect(groupingBy(Dish::getType, filtering(dish -> dish.getCalories() > 500, toList())));
42-
}
41+
// return menu.stream().collect(groupingBy(Dish::getType, filtering(dish -> dish.getCalories() > 500, toList())));
42+
// }
4343

4444
private static Map<CaloricLevel, List<Dish>> groupDishesByCaloricLevel() {
4545
return menu.stream().collect(
@@ -63,16 +63,22 @@ private static Map<Dish.Type, Map<CaloricLevel, List<Dish>>> groupDishedByTypeAn
6363
}
6464

6565
private static Map<Dish.Type, Long> countDishesInGroups() {
66+
Map<Dish.Type, Long> collect = menu.stream().collect(groupingBy(Dish::getType, counting()));
6667
return menu.stream().collect(groupingBy(Dish::getType, counting()));
6768
}
6869

6970
private static Map<Dish.Type, Optional<Dish>> mostCaloricDishesByType() {
71+
menu.stream().collect(groupingBy(Dish::getType, reducing((d1, d2) -> d1.getCalories() > d2.getCalories() ? d1 : d2)));
72+
73+
7074
return menu.stream().collect(
7175
groupingBy(Dish::getType,
7276
reducing((Dish d1, Dish d2) -> d1.getCalories() > d2.getCalories() ? d1 : d2)));
7377
}
7478

7579
private static Map<Dish.Type, Dish> mostCaloricDishesByTypeWithoutOprionals() {
80+
81+
7682
return menu.stream().collect(
7783
groupingBy(Dish::getType,
7884
collectingAndThen(
@@ -86,6 +92,8 @@ private static Map<Dish.Type, Integer> sumCaloriesByType() {
8692
}
8793

8894
private static Map<Dish.Type, Set<CaloricLevel>> caloricLevelsByType() {
95+
96+
8997
return menu.stream().collect(
9098
groupingBy(Dish::getType, mapping(
9199
dish -> { if (dish.getCalories() <= 400) return CaloricLevel.DIET;
Lines changed: 104 additions & 103 deletions
Original file line numberDiff line numberDiff line change
@@ -1,106 +1,107 @@
1-
//package lambdasinaction.chap6;
2-
//
3-
//import java.util.*;
4-
//import java.util.function.*;
5-
//import java.util.stream.*;
6-
//
7-
//import static java.util.stream.Collectors.*;
8-
//import static java.util.stream.Collector.Characteristics.*;
9-
//
10-
//public class PartitionPrimeNumbers {
11-
//
12-
// public static void main(String ... args) {
13-
// System.out.println("Numbers partitioned in prime and non-prime: " + partitionPrimes(100));
1+
package lambdasinaction.chap6;
2+
3+
import java.util.*;
4+
import java.util.function.*;
5+
import java.util.stream.*;
6+
7+
import static java.util.stream.Collectors.*;
8+
import static java.util.stream.Collector.Characteristics.*;
9+
10+
public class PartitionPrimeNumbers {
11+
12+
public static void main(String ... args) {
13+
System.out.println("Numbers partitioned in prime and non-prime: " + partitionPrimes(100));
1414
// System.out.println("Numbers partitioned in prime and non-prime: " + partitionPrimesWithCustomCollector(100));
15-
//
16-
// }
17-
//
18-
// public static Map<Boolean, List<Integer>> partitionPrimes(int n) {
19-
// return IntStream.rangeClosed(2, n).boxed()
20-
// .collect(partitioningBy(candidate -> isPrime(candidate)));
21-
// }
22-
//
23-
// public static boolean isPrime(int candidate) {
24-
// return IntStream.rangeClosed(2, candidate-1)
25-
// .limit((long) Math.floor(Math.sqrt((double) candidate)) - 1)
26-
// .noneMatch(i -> candidate % i == 0);
27-
// }
28-
//
29-
// public static Map<Boolean, List<Integer>> partitionPrimesWithCustomCollector(int n) {
30-
// return IntStream.rangeClosed(2, n).boxed().collect(new PrimeNumbersCollector());
31-
// }
32-
//
33-
// public static boolean isPrime(List<Integer> primes, Integer candidate) {
15+
16+
}
17+
18+
public static Map<Boolean, List<Integer>> partitionPrimes(int n) {
19+
return IntStream.rangeClosed(2, n).boxed()
20+
.collect(partitioningBy(candidate -> isPrime(candidate)));
21+
}
22+
23+
public static boolean isPrime(int candidate) {
24+
return IntStream.rangeClosed(2, candidate-1)
25+
.limit((long) Math.floor(Math.sqrt((double) candidate)) - 1)
26+
.noneMatch(i -> candidate % i == 0);
27+
}
28+
29+
public static Map<Boolean, List<Integer>> partitionPrimesWithCustomCollector(int n) {
30+
return IntStream.rangeClosed(2, n).boxed().collect(new PrimeNumbersCollector());
31+
}
32+
33+
public static boolean isPrime(List<Integer> primes, Integer candidate) {
3434
// double candidateRoot = Math.sqrt((double) candidate);
35-
// //return takeWhile(primes, i -> i <= candidateRoot).stream().noneMatch(i -> candidate % i == 0);
35+
//return takeWhile(primes, i -> i <= candidateRoot).stream().noneMatch(i -> candidate % i == 0);
3636
// return primes.stream().takeWhile(i -> i <= candidateRoot).noneMatch(i -> candidate % i == 0);
37-
// }
38-
///*
39-
// public static <A> List<A> takeWhile(List<A> list, Predicate<A> p) {
40-
// int i = 0;
41-
// for (A item : list) {
42-
// if (!p.test(item)) {
43-
// return list.subList(0, i);
44-
// }
45-
// i++;
46-
// }
47-
// return list;
48-
// }
49-
//*/
50-
// public static class PrimeNumbersCollector
51-
// implements Collector<Integer, Map<Boolean, List<Integer>>, Map<Boolean, List<Integer>>> {
52-
//
53-
// @Override
54-
// public Supplier<Map<Boolean, List<Integer>>> supplier() {
55-
// return () -> new HashMap<Boolean, List<Integer>>() {{
56-
// put(true, new ArrayList<Integer>());
57-
// put(false, new ArrayList<Integer>());
58-
// }};
59-
// }
60-
//
61-
// @Override
62-
// public BiConsumer<Map<Boolean, List<Integer>>, Integer> accumulator() {
63-
// return (Map<Boolean, List<Integer>> acc, Integer candidate) -> {
64-
// acc.get( isPrime( acc.get(true),
65-
// candidate) )
66-
// .add(candidate);
67-
// };
68-
// }
69-
//
70-
// @Override
71-
// public BinaryOperator<Map<Boolean, List<Integer>>> combiner() {
72-
// return (Map<Boolean, List<Integer>> map1, Map<Boolean, List<Integer>> map2) -> {
73-
// map1.get(true).addAll(map2.get(true));
74-
// map1.get(false).addAll(map2.get(false));
75-
// return map1;
76-
// };
77-
// }
78-
//
79-
// @Override
80-
// public Function<Map<Boolean, List<Integer>>, Map<Boolean, List<Integer>>> finisher() {
81-
// return i -> i;
82-
// }
83-
//
84-
// @Override
85-
// public Set<Characteristics> characteristics() {
86-
// return Collections.unmodifiableSet(EnumSet.of(IDENTITY_FINISH));
87-
// }
88-
// }
89-
//
90-
// public Map<Boolean, List<Integer>> partitionPrimesWithInlineCollector(int n) {
91-
// return Stream.iterate(2, i -> i + 1).limit(n)
92-
// .collect(
93-
// () -> new HashMap<Boolean, List<Integer>>() {{
94-
// put(true, new ArrayList<Integer>());
95-
// put(false, new ArrayList<Integer>());
96-
// }},
97-
// (acc, candidate) -> {
98-
// acc.get( isPrime(acc.get(true), candidate) )
99-
// .add(candidate);
100-
// },
101-
// (map1, map2) -> {
102-
// map1.get(true).addAll(map2.get(true));
103-
// map1.get(false).addAll(map2.get(false));
104-
// });
105-
// }
106-
//}
37+
return false;
38+
}
39+
/*
40+
public static <A> List<A> takeWhile(List<A> list, Predicate<A> p) {
41+
int i = 0;
42+
for (A item : list) {
43+
if (!p.test(item)) {
44+
return list.subList(0, i);
45+
}
46+
i++;
47+
}
48+
return list;
49+
}
50+
*/
51+
public static class PrimeNumbersCollector
52+
implements Collector<Integer, Map<Boolean, List<Integer>>, Map<Boolean, List<Integer>>> {
53+
54+
@Override
55+
public Supplier<Map<Boolean, List<Integer>>> supplier() {
56+
return () -> new HashMap<Boolean, List<Integer>>() {{
57+
put(true, new ArrayList<Integer>());
58+
put(false, new ArrayList<Integer>());
59+
}};
60+
}
61+
62+
@Override
63+
public BiConsumer<Map<Boolean, List<Integer>>, Integer> accumulator() {
64+
return (Map<Boolean, List<Integer>> acc, Integer candidate) -> {
65+
acc.get( isPrime( acc.get(true),
66+
candidate) )
67+
.add(candidate);
68+
};
69+
}
70+
71+
@Override
72+
public BinaryOperator<Map<Boolean, List<Integer>>> combiner() {
73+
return (Map<Boolean, List<Integer>> map1, Map<Boolean, List<Integer>> map2) -> {
74+
map1.get(true).addAll(map2.get(true));
75+
map1.get(false).addAll(map2.get(false));
76+
return map1;
77+
};
78+
}
79+
80+
@Override
81+
public Function<Map<Boolean, List<Integer>>, Map<Boolean, List<Integer>>> finisher() {
82+
return i -> i;
83+
}
84+
85+
@Override
86+
public Set<Characteristics> characteristics() {
87+
return Collections.unmodifiableSet(EnumSet.of(IDENTITY_FINISH));
88+
}
89+
}
90+
91+
public Map<Boolean, List<Integer>> partitionPrimesWithInlineCollector(int n) {
92+
return Stream.iterate(2, i -> i + 1).limit(n)
93+
.collect(
94+
() -> new HashMap<Boolean, List<Integer>>() {{
95+
put(true, new ArrayList<Integer>());
96+
put(false, new ArrayList<Integer>());
97+
}},
98+
(acc, candidate) -> {
99+
acc.get( isPrime(acc.get(true), candidate) )
100+
.add(candidate);
101+
},
102+
(map1, map2) -> {
103+
map1.get(true).addAll(map2.get(true));
104+
map1.get(false).addAll(map2.get(false));
105+
});
106+
}
107+
}

src/main/java/lambdasinaction/chap6/Partitioning.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
public class Partitioning {
1010

11-
public static void main(String ... args) {
11+
public static void main(String... args) {
1212
System.out.println("Dishes partitioned by vegetarian: " + partitionByVegeterian());
1313
System.out.println("Vegetarian Dishes by type: " + vegetarianDishesByType());
1414
System.out.println("Most caloric dishes by vegetarian: " + mostCaloricPartitionedByVegetarian());
@@ -23,6 +23,10 @@ private static Map<Boolean, Map<Dish.Type, List<Dish>>> vegetarianDishesByType()
2323
}
2424

2525
private static Object mostCaloricPartitionedByVegetarian() {
26+
27+
Map<Boolean, Dish> collect = menu.stream().collect(partitioningBy(Dish::isVegetarian, collectingAndThen(maxBy(comparingInt(Dish::getCalories)), Optional::get)));
28+
System.out.println(collect);
29+
2630
return menu.stream().collect(
2731
partitioningBy(Dish::isVegetarian,
2832
collectingAndThen(

src/main/java/lambdasinaction/chap6/Reducing.java

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
11
package lambdasinaction.chap6;
22

3+
import java.util.function.BiFunction;
4+
35
import static java.util.stream.Collectors.*;
46
import static lambdasinaction.chap6.Dish.menu;
57

68
public class Reducing {
79

8-
public static void main(String ... args) {
10+
public static void main(String... args) {
911
System.out.println("Total calories in menu: " + calculateTotalCalories());
1012
System.out.println("Total calories in menu: " + calculateTotalCaloriesWithMethodReference());
1113
System.out.println("Total calories in menu: " + calculateTotalCaloriesWithoutCollectors());
1214
System.out.println("Total calories in menu: " + calculateTotalCaloriesUsingSum());
15+
System.out.println("Total calories in menu: " + oldCount());
1316
}
1417

1518
private static int calculateTotalCalories() {
@@ -27,4 +30,17 @@ private static int calculateTotalCaloriesWithoutCollectors() {
2730
private static int calculateTotalCaloriesUsingSum() {
2831
return menu.stream().mapToInt(Dish::getCalories).sum();
2932
}
33+
34+
private static int oldCount() {
35+
menu.stream().map(Dish::getCalories).reduce(Integer::sum);
36+
menu.stream().mapToInt(Dish::getCalories).sum();
37+
38+
menu.stream().collect(reducing(0, Dish::getCalories, Integer::sum));
39+
40+
int sum = 0;
41+
for (Dish dish : menu) {
42+
sum += dish.getCalories();
43+
}
44+
return sum;
45+
}
3046
}

src/main/java/lambdasinaction/chap6/ToListCollector.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ public class ToListCollector<T> implements Collector<T, List<T>, List<T>> {
99

1010
@Override
1111
public Supplier<List<T>> supplier() {
12+
1213
return () -> new ArrayList<T>();
1314
}
1415

0 commit comments

Comments
 (0)