OptionalInt Example

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

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

getAsInt

@Test
public void optional_int_getAsInt() {

    OptionalInt optionalInt = OptionalInt.of(90);
    
    assertEquals(90, optionalInt.getAsInt(), 0);
}

ifPresent

@Test
public void optional_int_ifPresent() {
    
    OptionalInt optionalInt = OptionalInt.of(56);

    optionalInt.ifPresent(p -> System.out.println(p));
    
    // or
    
    optionalInt.ifPresent(System.out::println);
}

isPresent

@Test
public void optional_int_isPresent() {
    
    OptionalInt optionalInt = OptionalInt.of(56);
    
    assertTrue(optionalInt.isPresent());
}

orElse

@Test
public void optional_int_orElse() {
    
    OptionalInt optionalInt = OptionalInt.empty();
    
    assertEquals(77, optionalInt.orElse(77), 0);
}

orElseGet

@Test
public void optional_int_orElseGet() {
    
    OptionalInt optionalInt = OptionalInt.empty();

    assertEquals(10, optionalInt.orElseGet(() -> 10), 0);
    
    // or 
    IntSupplier intSupplier = new IntSupplier() {
        @Override
        public int getAsInt() {
            return 10;
        }
    };
    
    assertEquals(10, optionalInt.orElseGet(intSupplier), 0);
}

orElseThrow

@Test(expected=IllegalStateException.class)
public void optional_int_orElseThrow() {
    
    OptionalInt optionalFramework = OptionalInt.empty();

    optionalFramework.orElseThrow(IllegalStateException::new);
}

empty

@Test
public void optional_int_empty() {

    OptionalInt optionalInt = OptionalInt.empty();
    
    assertFalse(optionalInt.isPresent());
}

of

@Test
public void optional_int_of() {

    OptionalInt optionalInt = OptionalInt.of(89);
    
    assertEquals(89, optionalInt.getAsInt(), 0);
}