12/14/2018

[Java8] Optional

Java 8 SE introduces a new class called Optional that is inspired from Haskell and Scala. It's a class that encapsulates an option value. We can view Optional as a single value that either contains a value or not.

From Java definition

A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

Here are some test cases.

Creates the non-null and null value optional.

  @Test
   public void testCreate_NonNull_null_Optionals()
   {
      Optional<String> country = Optional.of("Taiwan");
      Assertions.assertTrue(country.isPresent());
      Assertions.assertEquals("Taiwan", country.get());

      Assertions.assertEquals(false, Optional.ofNullable(null).isPresent());
      Assertions.assertEquals("defaultValue", Optional.ofNullable(null).orElse("defaultValue"));
   }

Return value if present, otherwise return other.

   @Test
   public void testGetElseOption()
   {
      Optional<Date> current = Optional.ofNullable(null);
      Assertions.assertNotNull(current.orElse(new Date()));
   }
   

Return the value if present, otherwise invoke other and return the result of that invocation.

   @Test
   public void testOrElseGet()
   {
      Date dateNow = null;
Assertions.assertNotNull(Optional.ofNullable(dateNow).orElseGet(Date::new));
   }

Return the contained value, if present, otherwise throw an exception to be created by the provided supplier.

   @Test
   public void testOrElseThrow()
   {
      Date dateNow = null;
      Assertions.assertThrows(IllegalArgumentException.class, 
         () -> Optional.ofNullable(dateNow).orElseThrow(IllegalArgumentException::new));
   }

If a value is present, and the value matches the given predicate, return a describing the value, otherwise return an empty.

   @Test
   public void testFilter()
   {
      Optional<String> taipeiCity = Optional.of("Taipei").filter((v) -> v.contains("No.1 City"));
      Assertions.assertEquals(Optional.empty(), taipeiCity);

      Optional<String> county = Optional.of("Taiwan").filter(v -> v.contains("Taiwan"));
      Assertions.assertEquals("Taiwan", county.get());
   }

If a value is present, apply the provided {@code Optional}-bearing mapping function to it, return that result, otherwise return an empty {@code Optional}

   @Test
   public void testFlatMap()
   {
      Optional<Integer> numOp = Optional.of("111").flatMap(v -> Optional.of(Integer.valueOf(v)));
      Assertions.assertEquals(Integer.valueOf(111), numOp.get());
   }

In Java8 Optional is often be misused, optionals are not as easy as they seem. This tutorial will help us to avoid doing stupid code.

26 Reasons Why Using Optional Correctly Is Not Optional

No comments:

Post a Comment