package Option;
public class Computer {
private Soundcard soundcard;
public Computer() {
}
public Computer(Soundcard soundcard) {
this.soundcard = soundcard;
}
public Soundcard getSoundcard() {
return soundcard;
}
public void setSoundcard(Soundcard soundcard) {
this.soundcard = soundcard;
}
}
package Option;
import java.util.Optional;
public class OptionalTest {
public static void main(String[] args) {
getVersion2(new Computer(new Soundcard(new USB("3.0"))));
}
public static String getVersion0(Computer com) {
String v = com.getSoundcard().getUsb().getVersion();
return v == null ? "UNKNOWN" : v;
}
private static String getVersion1(Computer com) {
String version = "UNKNOWN";
if (com != null) {
Soundcard soundcard = com.getSoundcard();
if (soundcard != null) {
USB usb = soundcard.getUsb();
if (usb != null) {
version = usb.getVersion();
}
}
}
return version;
}
private static void ifPresent(USB usb) {
Optional<USB> usbOP = Optional.ofNullable(usb);
usbOP.ifPresent(u -> System.out.println(u.getVersion()));
Optional.ofNullable(usb)
.ifPresent(u -> System.out.println(u.getVersion()));
System.out.println("dfsf");
Optional.ofNullable(new Computer())
.ifPresent(c -> System.out.println(c.getSoundcard().getUsb()));
}
private static void ifPresentOrElse(USB usb) {
Optional.ofNullable(usb)
.ifPresentOrElse(u -> System.out.println(u.getVersion()),
() -> System.out.println("dfdf"));
}
private static void filter(USB usb) {
Optional.ofNullable(usb)
.filter(u -> "3.0".equals(u.getVersion()))
.ifPresent(u -> System.out.println(u.getVersion()));
}
private static void map(USB usb) {
Optional.ofNullable(usb)
.map(USB::getVersion)
.ifPresent(System.out::println);
}
private static void or(USB usb) {
Optional.of(usb)
.filter(u -> !"UNKNOWN".equals(u.getVersion()))
.or(() -> {
return Optional.of(new USB("1.1"));
})
.ifPresent(u -> System.out.println(u.getVersion()));
}
private static void orElse(USB usb) {
String v1 = Optional.ofNullable(usb)
.orElseGet(() -> {
return new USB("1.1");
}).getVersion();
System.out.println(v1);
String v2 = Optional.ofNullable(usb)
.orElse(new USB("1.1"))
.getVersion();
System.out.println(v2);
}
private static void Get(USB usb) {
String v = Optional.ofNullable(usb)
.or(() -> {
System.out.println("怎么会没有呢");
return Optional.of(new USB("1.1"));
})
.get()
.getVersion();
}
private static void getVersion2(Computer com) {
String v = Optional.ofNullable(com)
.map(Computer::getSoundcard)
.map(Soundcard::getUsb)
.map(USB::getVersion)
.orElse("UNKNOWN");
System.out.println(v);
}
package Option;
public class Soundcard {
private USB usb;
public Soundcard() {
}
public Soundcard(USB usb) {
this.usb = usb;
}
public USB getUsb() {
return usb;
}
public void setUsb(USB usb) {
this.usb = usb;
}
}
package Option;
public class USB {
private String version;
public USB() {
}
public USB(String version) {
this.version = version;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}