forked from igor-baiborodine/java-various-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReductionExample.java
More file actions
57 lines (45 loc) · 1.32 KB
/
ReductionExample.java
File metadata and controls
57 lines (45 loc) · 1.32 KB
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
package com.kiroule.ocpupgradejava8.topic5_2;
import java.util.Arrays;
import java.util.List;
/**
* @author Igor Baiborodine
*/
public class ReductionExample {
public static void main(String... args) {
List<FuturamaCharacter> characters = Arrays.asList(
new FuturamaCharacter("Bender", "Rodriguez", 5),
new FuturamaCharacter("Philip", "Fry", 126),
new FuturamaCharacter("Turanga", "Leela", 22));
System.out.println("Futurama characters:");
characters.forEach(c -> System.out.println(c));
int sumAge = characters
.stream()
.parallel()
.mapToInt(FuturamaCharacter::getAge)
.sum();
System.out.println("\nSum of ages: " + sumAge);
int sumAgeReduce = characters
.stream()
.parallel()
.map(FuturamaCharacter::getAge)
.reduce(0, (a, b) -> a + b);
System.out.println("\nSum of ages with reduce: " + sumAgeReduce);
}
}
class FuturamaCharacter {
private String firstName;
private String lastName;
private int age = 0;
public FuturamaCharacter(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return firstName + " " + lastName + " [" + age + "]";
}
}