Use Optionals as Streams

 class​ BackupJob {
 
  Communicator communicator;
  Storage storage;
 
 void​ backupToEarth() {
  Optional<Connection> connectionOptional =
  communicator.getConnectionToEarth();
»if​ (!connectionOptional.isPresent()) {
 throw​ ​new​ IllegalStateException();
  }
 
» Connection connection = connectionOptional.get();
 if​ (!connection.isFree()) {
 throw​ ​new​ IllegalStateException();
  }
 
  connection.send(storage.getBackup());
  }
 }

In the previous comparisons, we’ve shown that Optional can be a good replacement for null. But it’s not just that, and there’s a good reason why the class was added to lambda expressions in Java. An Optional is also a special kind of stream, one with either zero or exactly one ...

Get Java By Comparison now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.