I have read a lot of Java 8 Optional and I do understand the concept, but still get difficulties when trying to implement it myself in my code.
Although I have serached the web for good examples, I didn't found one with good explanation.
I have the next method:
public static String getFileMd5(String filePath) throws NoSuchAlgorithmException, IOException {
AutomationLogger.getLog().info("Trying getting MD5 hash from file: " + filePath);
MessageDigest md = MessageDigest.getInstance("MD5");
InputStream inputStream;
try {
inputStream = Files.newInputStream(Paths.get(filePath));
} catch (NoSuchFileException e) {
AutomationLogger.getLog().error("No such file path: " + filePath, e);
return null;
}
DigestInputStream dis = new DigestInputStream(inputStream, md);
byte[] buffer = new byte[8 * 1024];
while (dis.read(buffer) != -1);
dis.close();
inputStream.close();
byte[] output = md.digest();
BigInteger bi = new BigInteger(1, output);
String hashText = bi.toString(16);
return hashText;
}
This simple method returns the md5 of a file, by passing it the file path. As you can notice, if the file path doesn't exists (or wrong typed) a NoSuchFileException get thrown and the method return Null.
Instead of returning null, I want to use Optional, so my method should return Optional <String>
, right?
orElse()
, or this
kind of method should be used by the client side?To return the value of an optional, or a default value if the optional has no value, you can use orElse(other) . Note that I rewrote your code for finding the longest name: you can directly use max(comparator) with a comparator comparing the length of each String.
But instead of declaring the field as Optional, you can use the getter method returns the Optional<String> value using Optional. ofNullable(this. firstName).
The ofNullable() method of java. util. Optional class in Java is used to get an instance of this Optional class with the specified value of the specified type. If the specified value is null, then this method returns an empty instance of the Optional class.
Optional class in Java is used to get an empty instance of this Optional class. This instance do not contain any value. Parameters: This method accepts nothing. Return value: This method returns an empty instance of this Optional class.
Right.
public static Optional<String> getFileMd5(String filePath)
throws NoSuchAlgorithmException, IOException {
return Optional.empty(); // I.o. null
return Optional.of(nonnullString);
}
Usage:
getFileMd5(filePath).ifPresent((s) -> { ... });
or (less nice as undoing the Optional)
String s = getFileMd5(filePath).orElse("" /* null */);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With