Hacker Newsnew | comments | show | ask | jobs | submit login

There are several ways of doing it concisely with the Java Optional

  import java.util.Optional;

  public class Scratch {
      public static void main(String... args) {
          Optional<String> foo = Optional.of("foo");
          Optional<String> bar = Optional.empty();

          System.out.println(foo.orElse("Error"));
          System.out.println(bar.orElse("Error"));

          foo.map(Print::print).orElseGet(() -> Print.print("Error"));
          bar.map(Print::print).orElseGet(() -> Print.print("Error"));

          foo.ifPresent(Print::print);

      }

      static class Print {
          public static <T> T print(T val) {
              System.out.println(val);
              return val;
          }
      }
  }



Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact

Search: