/** * The filter method takes a predicate as an argument. * If a value is present in the Optional object and it matches the predicate, the filter method returns that value; * otherwise, it returns an empty Optional object. **/ Optional<USB> maybeUSB = ...; maybeUSB.filter(usb -> "3.0".equals(usb.getVersion()) .ifPresent(() -> System.out.println("ok"));
// extracting and transforming values using map, nothing happens if Optional object is empty Optional<USB> usb = maybeSoundcard.map(Soundcard::getUSB);
/** * Optional also supports a flatMap method. * Its purpose is to apply the transformation function on the value of an Optional (just like the map operation does) and then flatten the * resulting two-level Optional into a single one **/ String version = computer.flatMap(Computer::getSoundcard) .flatMap(Soundcard::getUSB) .map(USB::getVersion) .orElse("UNKNOWN");