Skip to main content

Posts

Showing posts with the label Optional

Java 8 - Optional - Or Else Throw

orElseThrow operation throws an exception in cases where the optional is empty.The exception is obtained from a Supplier function.

@Slf4j
public class OrElseThrow {

   static Optional<Person> acquaintance_1 = Optional.ofNullable(null);

   @SneakyThrows
   public static void main(String[] args) {
     log.info("orElseThrow on optional throws an exception if optional is empty");

     acquaintance_1.orElseThrow(() -> new Exception("value not present"));
   }
}

Java 8 - Optional - Or Else Get

orElseGet operation provides a fallback value in cases where the optional is empty.The fallback value is obtained from a supplier function.

@Slf4j
public class OrElseGet {

   static Optional<Person> acquaintance_1 = Optional.ofNullable(null);

   public static void main(String[] args) {

     log.info("orElseGet on optional provides a fallback: " + acquaintance_1.orElseGet(() -> new Person("Tom", "Cruise")) );
   }
}

Java 8 - Optional - Or Else

orElse operation provides a fallback value in cases where the optional is empty.

@Slf4j
public class OrElse {

   static Optional<Person> acquaintance_1 = Optional.ofNullable(null);

   public static void main(String[] args) {

     log.info("orElse on optional provides a fallback: " + acquaintance_1.orElse(new Person("Tom", "Cruise")) );
   }
}

Java 8 - Optional - Map

map operation on an optional returns a transformation of the optional.This transformation does not mutate the original optional.

@Slf4j
public class Map {

   static Optional<Person> dj = Optional.of(new Person("DJ", "JimmyJack"));

   public static void main(String[] args) {

   @RequiredArgsConstructor
   @ToString
   class Mammal {
     final String firstName;
     final String lastName;
   }

   log.info("transforming optional of person to optional of mammal: " + dj.map(person -> new Mammal(person.getFirstName(), person.getLastName())) );

   log.info("map on optional does not mutate original optional: " + dj.get().getFirstName().equals("DJ") );

   }
}

Java 8 - Optional - Is Present

isPresent operation on an optional returns a boolean indicating whether or not the optional has a value.

@Slf4j
public class IsPresent {

   static Optional<Person> dj = Optional.of(new Person("DJ", "JimmyJack"));
   static Optional<Person> acquaintance_1 = Optional.ofNullable(null);

   public static void main(String[] args) {

     log.info("isPresent on an optional returns true if there's a value: " + dj.isPresent() );

     log.info("isPresent on an optional returns false if there's no value: " + acquaintance_1.isPresent() );

   }
}

Java 8 - Optional - If Present

ifPresent operation on an optional applies a Consumer function to the value of the optional. If the optional is empty, nothing happens.

@Slf4j
public class IfPresent {

   static Optional dj = Optional.of(new Person("DJ", "JimmyJack"));

   public static void main(String[] args) {

     log.info("ifPresent on an optional applies the consumer function");

     dj.ifPresent(person -> log.info(person.toString()));
   }
}

Java 8 - Optional - Get

get operation on an optional returns the value of the optional.If the optional is empty, exception is thrown.

@Slf4j
public class Get {

   static Optional<Person> dj = Optional.of(new Person("DJ", "JimmyJack"));
   static Optional<Person> usher_2 = Optional.empty();

   public static void main(String[] args) {

     log.info("get on an optional returns the value: " + dj.get() );

     log.info("get on an empty optional throws exception:");
     usher_2.get();
   }
}

Java 8 - Optional - Flat Map

When a transformation on an optional transforms such optional to an optional of optional, we use flatMap to flatten the result back to an optional.
@Slf4j
public class FlatMap {

   static Optional<Person> dj = Optional.of(new Person("DJ", "JimmyJack"));

   public static void main(String[] args) {

     log.info("flatMap on an option flattens the result to an optional value: " +

      dj.flatMap(person -> {

       if(person.getFirstName().equals("Paul"))
        return Optional.of(new Person("DJ_2", "JimmyJack"));

       return dj;
     })
    );

   }
}

Java 8 - Optional - Filter

Filter operation on an optional returns an optional if the predicate function is satisfied, otherwise it returns empty.
@Slf4j
public class Filter {

   static Optional<Person> dj = Optional.of(new Person("DJ", "JimmyJack"));

   public static void main(String[] args) {

     log.info("filter on an option returns an empty optional if predicate is not satisfied: " + dj.filter(person -> person.getFirstName().equals("Paul")) );

     log.info("filter on an option returns an optional if predicate is satisfied: " + dj.filter(person -> person.getFirstName().equals("DJ")) );
   }
}

Java 8 - Optional - Introduction

The optional data type is useful for representing an object which can have a null value.It prevents null pointer exceptions and also provides useful operations on the object.
public abstract class IntroductionToOptionals {

   /*
    * let's assume we are having a party, and the party could have a DJ, MC and Usher
    * It's best to represent them as optional as their presence at the party is really optional
   * */
   Optional dj = Optional.of(new Person("DJ", "JimmyJack"));
   Optional mc = Optional.of(new Person("MC", "Hammer"));
   Optional usher = Optional.of(new Person("Usher", "Ray"));

   /*
    * assuming there could be a second Usher who we can bet won't attend, we can set such
    * usher to an empty option
   */
   Optional usher_2 = Optional.empty();

   /*
    * assuming also that two acquaintances may attend the party, but we c…