OptionalLong Example

OptionalLong, a sister to OptionalInt and OptionalDouble, is a new class introduced in Java 8 which is a container object that may or may not contain a long value. If a long is present, isPresent() will return true and getAsLong() will return the value.

When dealing with non primitive values, see java.util.Optional example.

getAsLong

@Test
public void optional_long_getAsLong() {

    OptionalLong optionalLong = OptionalLong.of(90);

    assertEquals(90, optionalLong.getAsLong(), 0);
}

ifPresent

@Test
public void optional_long_ifPresent() {

    OptionalLong optionalLong = OptionalLong.of(56);

    optionalLong.ifPresent(p -> System.out.println(p));

    // or

    optionalLong.ifPresent(System.out::println);
}

isPresent

@Test
public void optional_long_isPresent() {

    OptionalLong optionalLong = OptionalLong.of(56);

    assertTrue(optionalLong.isPresent());
}

orElse

@Test
public void optional_long_orElse() {

    OptionalLong optionalLong = OptionalLong.empty();

    assertEquals(77, optionalLong.orElse(77), 0);
}

orElseGet

@Test
public void optional_long_orElseGet() {

    OptionalLong optionalLong = OptionalLong.empty();

    assertEquals(10, optionalLong.orElseGet(() -> 10), 0);

    // or 
    LongSupplier longSupplier = new LongSupplier() {
        @Override
        public long getAsLong() {
            return 10;
        }
    };

    assertEquals(10, optionalLong.orElseGet(longSupplier), 0);
}

orElseThrow

@Test(expected=IllegalStateException.class)
public void optional_long_orElseThrow() {

    OptionalLong optionalFramework = OptionalLong.empty();

    optionalFramework.orElseThrow(IllegalStateException::new);
}

empty

@Test
public void optional_long_empty() {

    OptionalLong optionalLong = OptionalLong.empty();

    assertFalse(optionalLong.isPresent());
}

of

@Test
public void optional_long_of() {

    OptionalLong optionalLong = OptionalLong.of(89);

    assertEquals(89, optionalLong.getAsLong(), 0);
}