forked from igor-baiborodine/java-various-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculationsExample.java
More file actions
77 lines (62 loc) · 2.08 KB
/
CalculationsExample.java
File metadata and controls
77 lines (62 loc) · 2.08 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.kiroule.ocpupgradejava8.topic4_4;
import java.util.Arrays;
import java.util.List;
import java.util.OptionalDouble;
import java.util.OptionalInt;
/**
* @author Igor Baiborodine
*/
public class CalculationsExample {
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(System.out::println); // c -> System.out.println(c)
long count = characters
.stream()
.count();
System.out.println("\nCharacters count: " + count);
OptionalInt minAge = characters
.stream()
.mapToInt(FuturamaCharacter::getAge) // c -> c.getAge()
.min();
System.out.println("Characters min age: "
+ (minAge.isPresent() ? minAge.getAsInt() : "Not available"));
OptionalInt maxAge = characters
.stream()
.mapToInt(FuturamaCharacter::getAge)
.max();
System.out.println("Characters max age: "
+ (maxAge.isPresent() ? maxAge.getAsInt() : "Not available"));
OptionalDouble averageAge = characters
.stream()
.mapToDouble(FuturamaCharacter::getAge)
.average();
System.out.println("Characters average age: "
+ (averageAge.isPresent() ? averageAge.getAsDouble() : "Not available"));
int sumAge = characters
.stream()
.mapToInt(FuturamaCharacter::getAge)
.sum();
System.out.println("Characters sum of ages: " + sumAge);
}
}
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 + "]";
}
}