-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample187.java
More file actions
60 lines (50 loc) · 1.84 KB
/
Example187.java
File metadata and controls
60 lines (50 loc) · 1.84 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
// Example 187 from page 147
//
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
class Example187 {
public static void main(String[] args) {
Map<String,String> form = new HashMap<String,String>();
form.put("area", "144.0");
doubleExampleA(form);
doubleExampleB(form);
doubleExampleC(form);
}
public static void doubleExampleA(Map<String,String> form) {
String areaString = form.get("area"), toPrint = "No value";
if (areaString != null) {
try {
double areaValue = Double.parseDouble(areaString);
double result = Math.sqrt(areaValue);
if (!Double.isNaN(result))
toPrint = String.valueOf(result);
} catch (NumberFormatException exn) { }
}
System.out.println(toPrint);
}
public static void doubleExampleB(Map<String,String> form) {
Optional<String> areaString = Optional.<String>ofNullable(form.get("area"));
Optional<Double> areaValue = areaString.flatMap(s -> parseDouble(s));
Optional<Double> result = areaValue.flatMap(v -> sqrt(v));
System.out.println(result.map(String::valueOf).orElse("No value"));
}
public static void doubleExampleC(Map<String,String> form) {
String toPrint = Optional.<String>ofNullable(form.get("area"))
.flatMap(s -> parseDouble(s))
.flatMap(v -> sqrt(v))
.map(String::valueOf)
.orElse("No value");
System.out.println(toPrint);
}
public static Optional<Double> parseDouble(String s) {
try {
return Optional.<Double>of(Double.parseDouble(s));
} catch (NumberFormatException exn) {
return Optional.<Double>empty();
}
}
public static Optional<Double> sqrt(double x) {
return x < 0.0 ? Optional.<Double>empty() : Optional.<Double>of(Math.sqrt(x));
}
}