forked from jbloch/effective-java-3e-source-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParentPid.java
More file actions
19 lines (15 loc) · 688 Bytes
/
ParentPid.java
File metadata and controls
19 lines (15 loc) · 688 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package effectivejava.chapter8.item55;
import java.util.Optional;
// Avoiding unnecessary use of Optional's isPresent method (Page 252)
public class ParentPid {
public static void main(String[] args) {
ProcessHandle ph = ProcessHandle.current();
// Inappropriate use of isPresent
Optional<ProcessHandle> parentProcess = ph.parent();
System.out.println("Parent PID: " + (parentProcess.isPresent() ?
String.valueOf(parentProcess.get().pid()) : "N/A"));
// Equivalent (and superior) code using orElse
System.out.println("Parent PID: " +
ph.parent().map(h -> String.valueOf(h.pid())).orElse("N/A"));
}
}