Skip to content

Instantly share code, notes, and snippets.

View HDBandit's full-sized avatar

Gerard Vico HDBandit

View GitHub Profile
String audioSystemVersion = "UNKNOWN";
if (myCar != null) {
AudioSystem audioSystem = myCar.getAudioSystem();
if (audioSystem != null) { // the card has audio system.
audioSystemVersion = audioSystem.getVersion();
}
}
@HDBandit
HDBandit / EmptyOptional.java
Last active December 7, 2015 20:25
Empty Optional
Optional<AudioSystem> sc = Optional.empty();
@HDBandit
HDBandit / NonNullValue.java
Last active December 7, 2015 20:25
Optional with a non null value
AudioSystem audioSystem = new AudioSystem();
Optional<AudioSystem> as = Optional.of(audioSystem);
Optional<AudioSystem> as = Optional.ofNullable(audioSystem);
AudioSystem as = ....;
if (as != null) {
Sysmte.out.println(as);
}
Optional<AudioSystem> as = ...;
as.ifPresent(System.out::println);
Optional<AudioSystem> audioSystem = ...;
if(audioSystem.isPresent()){
System.out.println(audioSystem.get());
}
AudioSystem as = ...;
if(as != null && "Pionner".equals(as.getBrand())){
System.out.println(as);
}
Optional<AudioSystem> maybeAudioSystem = ...;
maybeAudioSystem.filter(as -> "Pionner".equals(as.getBrand())
.ifPresent(as -> System.out.println(as));
if(car != null){
AudioSystem as = car.getAudioSystem();
if(as != null && "Pionner".equals(as.getBrand()){
System.out.println("ok");
}
}