Skip to content

Commit 4786c46

Browse files
committed
changes for 2nd edition
1 parent ae8122f commit 4786c46

File tree

7 files changed

+158
-16
lines changed

7 files changed

+158
-16
lines changed

pom.xml

+32-3
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,16 @@
1313
</properties>
1414

1515
<dependencies>
16+
<dependency>
17+
<groupId>org.openjdk.jmh</groupId>
18+
<artifactId>jmh-core</artifactId>
19+
<version>1.17.4</version>
20+
</dependency>
21+
<dependency>
22+
<groupId>org.openjdk.jmh</groupId>
23+
<artifactId>jmh-generator-annprocess</artifactId>
24+
<version>1.17.4</version>
25+
</dependency>
1626
<dependency>
1727
<groupId>junit</groupId>
1828
<artifactId>junit</artifactId>
@@ -27,11 +37,30 @@
2737
<artifactId>maven-compiler-plugin</artifactId>
2838
<version>3.1</version>
2939
<configuration>
30-
<source>1.8</source>
31-
<target>1.8</target>
40+
<source>1.9</source>
41+
<target>1.9</target>
3242
</configuration>
3343
</plugin>
44+
<plugin>
45+
<groupId>org.apache.maven.plugins</groupId>
46+
<artifactId>maven-shade-plugin</artifactId>
47+
<executions>
48+
<execution>
49+
<phase>package</phase>
50+
<goals>
51+
<goal>shade</goal>
52+
</goals>
53+
<configuration>
54+
<finalName>benchmarks</finalName>
55+
<transformers>
56+
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
57+
<mainClass>org.openjdk.jmh.Main</mainClass>
58+
</transformer>
59+
</transformers>
60+
</configuration>
61+
</execution>
62+
</executions>
63+
</plugin>
3464
</plugins>
3565
</build>
36-
3766
</project>

src/main/java/lambdasinaction/chap10/OperationsWithOptional.java

+7
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,13 @@ public class OperationsWithOptional {
1010
public static void main(String... args) {
1111
System.out.println(max(of(3), of(5)));
1212
System.out.println(max(empty(), of(5)));
13+
14+
Optional<Integer> opt1 = of(5);
15+
Optional<Integer> opt2 = opt1.or(() -> of(4));
16+
17+
System.out.println(
18+
of(5).or(() -> of(4))
19+
);
1320
}
1421

1522
public static final Optional<Integer> max(Optional<Integer> i, Optional<Integer> j) {

src/main/java/lambdasinaction/chap10/OptionalMain.java

+11
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
import java.util.*;
44

5+
import static java.util.stream.Collectors.toSet;
6+
57
public class OptionalMain {
68

79
public String getCarInsuranceName(Optional<Person> person) {
@@ -10,4 +12,13 @@ public String getCarInsuranceName(Optional<Person> person) {
1012
.map(Insurance::getName)
1113
.orElse("Unknown");
1214
}
15+
16+
public Set<String> getCarInsuranceNames(List<Person> persons) {
17+
return persons.stream()
18+
.map(Person::getCar)
19+
.map(optCar -> optCar.flatMap(Car::getInsurance))
20+
.map(optInsurance -> optInsurance.map(Insurance::getName))
21+
.flatMap(Optional::stream)
22+
.collect(toSet());
23+
}
1324
}

src/main/java/lambdasinaction/chap6/Dish.java

+25-9
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
import java.util.*;
44

5+
import static java.util.Arrays.asList;
6+
57
public class Dish {
68

79
private final String name;
@@ -40,13 +42,27 @@ public String toString() {
4042
}
4143

4244
public static final List<Dish> menu =
43-
Arrays.asList( new Dish("pork", false, 800, Dish.Type.MEAT),
44-
new Dish("beef", false, 700, Dish.Type.MEAT),
45-
new Dish("chicken", false, 400, Dish.Type.MEAT),
46-
new Dish("french fries", true, 530, Dish.Type.OTHER),
47-
new Dish("rice", true, 350, Dish.Type.OTHER),
48-
new Dish("season fruit", true, 120, Dish.Type.OTHER),
49-
new Dish("pizza", true, 550, Dish.Type.OTHER),
50-
new Dish("prawns", false, 400, Dish.Type.FISH),
51-
new Dish("salmon", false, 450, Dish.Type.FISH));
45+
asList( new Dish("pork", false, 800, Dish.Type.MEAT),
46+
new Dish("beef", false, 700, Dish.Type.MEAT),
47+
new Dish("chicken", false, 400, Dish.Type.MEAT),
48+
new Dish("french fries", true, 530, Dish.Type.OTHER),
49+
new Dish("rice", true, 350, Dish.Type.OTHER),
50+
new Dish("season fruit", true, 120, Dish.Type.OTHER),
51+
new Dish("pizza", true, 550, Dish.Type.OTHER),
52+
new Dish("prawns", false, 400, Dish.Type.FISH),
53+
new Dish("salmon", false, 450, Dish.Type.FISH));
54+
55+
public static final Map<String, List<String>> dishTags = new HashMap<>();
56+
57+
static {
58+
dishTags.put("pork", asList("greasy", "salty"));
59+
dishTags.put("beef", asList("salty", "roasted"));
60+
dishTags.put("chicken", asList("fried", "crisp"));
61+
dishTags.put("french fries", asList("greasy", "fried"));
62+
dishTags.put("rice", asList("light", "natural"));
63+
dishTags.put("season fruit", asList("fresh", "natural"));
64+
dishTags.put("pizza", asList("tasty", "salty"));
65+
dishTags.put("prawns", asList("tasty", "roasted"));
66+
dishTags.put("salmon", asList("delicious", "fresh"));
67+
}
5268
}

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

+17
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import java.util.*;
44

55
import static java.util.stream.Collectors.*;
6+
import static lambdasinaction.chap6.Dish.dishTags;
67
import static lambdasinaction.chap6.Dish.menu;
78

89
public class Grouping {
@@ -11,6 +12,9 @@ enum CaloricLevel { DIET, NORMAL, FAT };
1112

1213
public static void main(String ... args) {
1314
System.out.println("Dishes grouped by type: " + groupDishesByType());
15+
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());
1418
System.out.println("Dishes grouped by caloric level: " + groupDishesByCaloricLevel());
1519
System.out.println("Dishes grouped by type and caloric level: " + groupDishedByTypeAndCaloricLevel());
1620
System.out.println("Count dishes in groups: " + countDishesInGroups());
@@ -24,6 +28,19 @@ private static Map<Dish.Type, List<Dish>> groupDishesByType() {
2428
return menu.stream().collect(groupingBy(Dish::getType));
2529
}
2630

31+
private static Map<Dish.Type, List<String>> groupDishNamesByType() {
32+
return menu.stream().collect(groupingBy(Dish::getType, mapping(Dish::getName, toList())));
33+
}
34+
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() {
40+
// 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+
}
43+
2744
private static Map<CaloricLevel, List<Dish>> groupDishesByCaloricLevel() {
2845
return menu.stream().collect(
2946
groupingBy(dish -> {

src/main/java/lambdasinaction/chap6/PartitionPrimeNumbers.java

+4-4
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,10 @@ public static Map<Boolean, List<Integer>> partitionPrimesWithCustomCollector(int
3232

3333
public static boolean isPrime(List<Integer> primes, Integer candidate) {
3434
double candidateRoot = Math.sqrt((double) candidate);
35-
//return primes.stream().filter(p -> p < candidateRoot).noneMatch(p -> candidate % p == 0);
36-
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);
36+
return primes.stream().takeWhile(i -> i <= candidateRoot).noneMatch(i -> candidate % i == 0);
3737
}
38-
38+
/*
3939
public static <A> List<A> takeWhile(List<A> list, Predicate<A> p) {
4040
int i = 0;
4141
for (A item : list) {
@@ -46,7 +46,7 @@ public static <A> List<A> takeWhile(List<A> list, Predicate<A> p) {
4646
}
4747
return list;
4848
}
49-
49+
*/
5050
public static class PrimeNumbersCollector
5151
implements Collector<Integer, Map<Boolean, List<Integer>>, Map<Boolean, List<Integer>>> {
5252

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package lambdasinaction.chap7;
2+
3+
import java.util.concurrent.TimeUnit;
4+
import java.util.stream.LongStream;
5+
import java.util.stream.Stream;
6+
7+
import org.openjdk.jmh.annotations.Benchmark;
8+
import org.openjdk.jmh.annotations.BenchmarkMode;
9+
import org.openjdk.jmh.annotations.Fork;
10+
import org.openjdk.jmh.annotations.Level;
11+
import org.openjdk.jmh.annotations.Measurement;
12+
import org.openjdk.jmh.annotations.Mode;
13+
import org.openjdk.jmh.annotations.OutputTimeUnit;
14+
import org.openjdk.jmh.annotations.Scope;
15+
import org.openjdk.jmh.annotations.State;
16+
import org.openjdk.jmh.annotations.TearDown;
17+
import org.openjdk.jmh.annotations.Warmup;
18+
19+
@State(Scope.Thread)
20+
@BenchmarkMode(Mode.AverageTime)
21+
@OutputTimeUnit(TimeUnit.MILLISECONDS)
22+
@Fork(value=2, jvmArgs={"-Xms4G", "-Xmx4G"})
23+
@Measurement(iterations=2)
24+
@Warmup(iterations=3)
25+
public class ParallelStreamBenchmark {
26+
27+
private static final long N = 10_000_000L;
28+
29+
@Benchmark
30+
public long iterativeSum() {
31+
long result = 0;
32+
for (long i = 1L; i <= N; i++) {
33+
result += i;
34+
}
35+
return result;
36+
}
37+
38+
@Benchmark
39+
public long sequentialSum() {
40+
return Stream.iterate( 1L, i -> i + 1 ).limit(N).reduce( 0L, Long::sum );
41+
}
42+
43+
@Benchmark
44+
public long parallelSum() {
45+
return Stream.iterate(1L, i -> i + 1).limit(N).parallel().reduce( 0L, Long::sum);
46+
}
47+
48+
@Benchmark
49+
public long rangedSum() {
50+
return LongStream.rangeClosed( 1, N ).reduce( 0L, Long::sum );
51+
}
52+
53+
@Benchmark
54+
public long parallelRangedSum() {
55+
return LongStream.rangeClosed(1, N).parallel().reduce( 0L, Long::sum);
56+
}
57+
58+
@TearDown(Level.Invocation)
59+
public void tearDown() {
60+
System.gc();
61+
}
62+
}

0 commit comments

Comments
 (0)